打印链表

Printing a linked list

我正在尝试学习 C++ 中的链表。我试图在列表中插入新节点并显示它们。 但是在显示链表时我得到一些随机的 values.The 程序继续运行并且根本没有停止。

#include<iostream>
using namespace std;
struct node
{
  int data;
  node *next;
};

int main()
{
  int ch;
  char ch1;
  do
  {

    cout<<"Enter your choice"<<endl;
    cout<<"1.Adding the first node"<<endl;
    cout<<"2.Adding a new node"<<endl;
    cout<<"3.Printing the list"<<endl;
    cin>>ch;
    node *n;
    node *t;
    node *h;
    switch(ch)
    {
      case 1:
        n=new node;
        int x;
        cout<<"Enter the value"<<endl;
        cin>>x;
        n->data=x;
        t=n;
        h=n;
        cout<<"Do you want to continue";
        cin>>ch1;
        break;

      case 2:
        n=new node;
        int y;
        cout<<"Enter the value"<<endl;
        cin>>y;
        n->data=y;
        t->next=n;
        t=t->next;
        cout<<"Do you want to continue";
        cin>>ch1;
        break;

      case 3:
        do
        {   while(h->next!=NULL)
          {


            cout<<h->data<<endl;
            h=h->next;
          }
        }while(h!=NULL);
        break;
    }
  }while(ch1=='y' || ch1=='Y');
}

您忘记将 next 设置为第一个节点:

case 1:
n=new node;
n->next = NULL;//this
int x;
cout<<"Enter the value"<<endl;
cin>>x;
n->data=x;
t=n;
h=n;
n->
cout<<"Do you want to continue";
cin>>ch1;
break;

最后一个节点也是:

case 2:
n=new node;
int y;
cout<<"Enter the value"<<endl;
cin>>y;
n->data=y;
n->next=NULL;//here too
t->next=n;
t=t->next;

cout<<"Do you want to continue";
cin>>ch1;
break;

除此之外,您正在遍历头指针 h=h->next; 以显示值,因此如果您尝试第二次显示列表,它将不会显示任何内容。 而是遍历头指针使用临时指针并更改条件 while(h->next!=NULL)while(t!=null) 以便显示列表中的最后一个元素

t=h;

while(t!=NULL)
{
    cout<<t->data<<endl;
    t=t->next;
}