c++ - 在 C++ 中打印链表的元素(参见代码)

标签 c++

我的问题是我正在尝试编写一个程序来动态生成(链接列表的)节点。一切顺利,但是当在底部我尝试使用 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/

相关文章:

c++ - 重复符号 XCode g++-4.2

c++ - Linux 上 STL 的安全版本

c++ - 当我们在模板声明中看到 class C = myarray 时,这意味着什么?

opengl - 代码::阻止对 "*"的 undefined reference

c++ - Visual C++ 2008 'Release' build 包含调试信息

c++ - 固定维数(N=9)、对称、半正定稠密线性系统的快速解

c++ - Tensorflow 和 Bazel C++

c++ - 问题将对象插入 vector

c++ - 关于包含不可复制成员引用的类的复制构造函数的建议

c++ - 纯虚函数,它是如何工作的