在遍历 link 列表以读取数据时,我的函数仅打印倒数第二个节点,建议一种打印整个列表的方法

While traversing the link list to read data my function prints up to penultimate node only, Suggest a way to print the whole list

我用C++做了一个链表。为此,我有一个名为:ListTraverse() 的函数。其中接受一个Node类型的指针变量,其中Node是my class。请给我一个打印到最后一个节点的方法。 这是函数调用:

ListTraverse(&head);

这里是函数定义:

void ListTraverse(Node* node)
{
//Prints upto penultimate node
  while (node->next != NULL)
  {
      cout << "\nNode details:\t"
         << node->read_data();
      node=node->next;
  }
}

这里有完整的代码。

#include <bits/stdc++.h>
#include <stdlib.h>
#include<typeinfo>
using namespace std;
class Node
{
  private:
  int data;

  public:
  Node *next;
  void push_data(int x)
{
    data = x;
}
int read_data()
{
    return data;
}
};
void ListTraverse(Node *);
int main()
{
 system("CLS");
 //Creating Node type variables
 Node head, second, tail;
int num, choice;
//Getting user input
cout << "Enter a number for head:\t";
cin >> num;
head.push_data(num);
cout << "Enter a number for second:\t";
cin >> num;
second.push_data(num);
cout << "Enter a number for tail:\t";
cin >> num;
tail.push_data(num);
//Assigning pointers to link up
head.next = &second;
second.next = &tail;
tail.next = NULL;
cout << "If you want to read data press 1:\t";
cin >> choice;
switch (choice)
{
case 1:
    ListTraverse(&head);
    break;
default:
    cout << "Invalid choice";
    break;
}
return 0;
}
 //Funtion to print Data
void ListTraverse(Node* node)
{
//Prints upto penultimate node
while (node->next != NULL)
{
    cout << "\nNode details:\t"
         << node->read_data();
    node=node->next;
}
}

您应该重新表述您的问题。好像

我的函数只打印倒数第二个节点

是问题所在。

您想打印整个列表,而不是倒数第二个。修复是

void ListTraverse(Node* node)
{
//Prints upto the last node
  while (node)
  {
      cout << "\nNode details:\t"
         << node->read_data();
      node=node->next;
  }
}