【发布时间】:2018-12-16 16:02:55
【问题描述】:
我编写此代码以自动获取值并将它们放入链表中,但它只维护第一个并替换第二个节点中的任何新值,并且不会生成第三个、第四个或 ... 节点。
#include <iostream>
using namespace std;
struct node
{
int a;
struct node *next;
}zero;
node *first = NULL;
int main()
{
int t;
for (int i = 0;i < 10;i++)
{
node *n = first;
cin >> t;
if (first == NULL)
{
node temp;
temp.a = t;
first = &temp;
temp.next = NULL;
}
else
{
while ((*n).next != NULL)
{
n = (*n).next;
}
node tt;
tt.a = t;
(*n).next = &tt;
tt.next = NULL;
}
}
}
我插入了 28。 我的第一个节点数据=28。 我插入了57。 我的第二个节点数据 = 57。 我插入了120。 我的 second 节点数据=120。 ...
【问题讨论】:
-
当您在调试器中启动程序并逐行执行代码时,您观察到了什么?
-
我知道它会出现在每次代码审查中,但是don't use
using namespace std -
由于悬空指针的取消引用(由于存储指向局部变量的指针)导致的未定义行为。
-
存储
&提供的内容以供以后使用通常是个坏主意。这也不例外。网络上到处都是链表的例子,书籍也是如此。 -
您使用指向局部变量的指针。你永远不会分配新的内存。
标签: c++ linked-list