Создание единого связанного списка C ++. Реализация - PullRequest
0 голосов
/ 07 октября 2019

Я довольно новичок в объектно-ориентированном программировании, и я пытаюсь завершить это задание, включающее вставку и удаление данных из связанного списка. Я думаю, что у меня работает создание узла, но я не могу понять, почему я не могу отобразить его. Я хочу убедиться, что узлы действительно добавляются, прежде чем я продолжу. Любая помощь будет высоко ценится!

#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();
}

1 Ответ

0 голосов
/ 07 октября 2019

Чтобы напечатать список, вам нужно использовать while с тем же условием в вашей функции displayList(). Цикл while, работающий над списком до тех пор, пока node->next не будет указывать на значение NULL (что означает, что это конец списка).

В main() вам нужно только инициализировать одноПеречислите и добавьте в него все значения.

Кроме того, рекомендация стиля кода должна начинаться с заглавной буквы и иметь заглавную букву для каждого нового слова. Полезно различать функции и классы, например:

class MyClass
{

};

struct MyStruct
{

};

Код выглядит так:

#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;

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

};

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

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

  //Whre the display calss member function is called
  first.displayList();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...