我的问题是我正在尝试编写一个程序来动态生成(链接列表的)节点。一切顺利,但是当在底部我尝试使用 while 循环打印链接列表的元素时:while(ptr->next !=NULL)
,程序只打印第一个元素。
(是的,我在循环中提到了 ptr=ptr->next
)
这是我的代码:
struct node {
int item;
node *next;
}
;
main() {
int a,b,c=0;
node *head,*tail,*ptr, *temp;
ptr = new node;
ptr->item = 0;
ptr->next = NULL;
head= ptr;
ptr->next=tail;
for (int i=0;1;i++) {
cout<<" Enter 1 if u want to make another node\n Enter 2 to stop making nodes\n";
cin>>a;
if(a==1) {
if(c!=0) {
ptr = new node;
cout<<"Enter new element at the new node:\n";
cin>>b;
ptr->item = b;
ptr->next = NULL;
tail = ptr;
}
if(c==0) {
ptr = new node;
cout<<"Enter new element at the new node:\n";
cin>>b;
ptr->item = b;
head->next= ptr;
ptr->next = NULL;
tail = ptr;
c++;
}
} else if(a==2) {
break;
}
}
ptr=head;
while(ptr->next != NULL) {
ptr=ptr->next;
cout<<" element: "<<ptr->item<<endl;
}
}
最佳答案
我的编译器(带有标志 -Wall -Wextra -pedantic 的 g++ 4.8)已经解决了这个问题:
warning: ‘tail’ is used uninitialized in this function [-Wuninitialized]
你接下来要更新,但是有一个未初始化的变量 tail。
关于c++ - 在 C++ 中打印链表的元素(参见代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32726453/