dimanche 6 octobre 2019

I need help programming a C++ single linked list

I am pretty new to object oriented programming and I am trying to finish this hw assignment involving inserting and removing data from a linked list. I think I have the node creation working but I can't figure out why I can't display it. I want to make sure the nodes are actually being added before I keep going. Any help would be much appreciated!!

#include <iostream>
using namespace std;

//void addNode(int num);
//void displayList();

struct node{
  //Where the data within the node is intialized
  int data;

  //Where the node advancement pointer is intialized
  node *next;
};

class list{
 private:
  //Where the head and tail pointers are intialized, these will hold the first and last node (in order to not lose track)
  node *head,*tail;

  public:
  //The constructor (for the class)
  list()
  {
    //Where the node header is set to NULL
    head=NULL;
    //Where the node tail is set to NULL
    tail=NULL;
  }

  void addNode(int num)
  {
    //A temp node is made by calling the node struct
    node *temp=new node;

    //The user entered number is added to the data portion of the node in the list
    temp->data=num;
    //The new tail is made and pointed to
    temp->next=NULL;


    if(head == NULL)
      {
        //If the data being entered is the first node
        //First andlast nodes is the data being entered
        head = temp;
        tail = temp;
      }
    else
    {
      //Set node after tail (last node) equal to the data being entered
      tail->next = temp;
      //Set the tail (last node) equal to the node after temp
      tail = tail->next;
    }
  }

  void displayList()
  {
    node *displayNode=new node;
    displayNode=head;

    if(displayNode!=NULL)
    {
      cout<<"display list";
      cout<<displayNode->data<<endl;
      displayNode=displayNode->next;
    }
  }

};

int main() {
  //Creating arguments for the list class
  list first;
  list second;
  list third;

  //Where the class member functions are called with the data 1, 2, and 3
  first.addNode(1);
  second.addNode(2);
  third.addNode(3);

  //Whre the display calss member function is called
  list print;
  print.displayList();
}

Aucun commentaire:

Enregistrer un commentaire