我正在尝试用C++学习Linkedlist。我试图在列表中插入新节点并显示它们。但是在显示链表时,我得到了一些随机值。程序继续运行,根本不停止。
#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');
}
您忘记在第一个节点的 null 旁边设置:
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;
}