【发布时间】:2021-09-06 22:03:04
【问题描述】:
在下面的代码中,我在最后一个节点处插入。它工作正常。 但我的疑问是因为我最后声明了 Node *;本地,因此每当进行新调用时,都会创建一个新的指针变量,并在函数终止后从内存中删除前一个变量。那么 Node * 是怎么来的?是否保留了上一次调用的地址,因为每次都会重新创建?
第一;是指向链表第一个节点的指针,全局声明。
void insertLast(int x)
{
Node *last;
Node *q=new Node;
q->data=x;
q->next=NULL;
if(first==NULL)
first=last=q;
else
{
last->next=q;
last=q;
}
}
insertLast(2);
insertLast(5);
insertLast(7);
display(first);
output:
2 5 7
【问题讨论】:
-
请在问题中包含您的代码的minimal reproducible example
-
last->next=q;行是未定义的行为,因为此时last未初始化。 -
那么为什么 Node * 是最后一个?正在保存上一次调用的地址 - 未定义的行为。它很可能只起作用,因为您连续进行调用并且值保存在寄存器/堆栈中未清除。如果您在
display之后再添加一个insertLast调用,它可能会崩溃。 -
@463035818_is_not_a_number 我已经更新了帖子。请再次检查。
-
@Yksisarvinen 我在显示后尝试添加。仍然可以正常工作。
标签: c++ pointers struct linked-list structure