gpt4 book ai didi

c - 链表删除节点。 Free(pointer) 在下一个节点打印 0

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:07 26 4
gpt4 key购买 nike

下面是链接列表代码中的一个删除节点,它将头指针和要删除的位置作为参数(链接列表中的位置索引从零开始)。并在删除后,返回一个指向 head 的指针。

Node* delete(Node* head, int position) 
{
Node *p = head;
if(!position)
{
p = p->next;
}
else
{
while(position--)
{
if(!position) head->next = head->next->next;
head = head->next;
}
}
free(head);
return p;
}

假设列表:20-2-19-7-3-6。要删除的位置是 2(要删除的节点 19,因为索引从零开始)。

删除并打印后,它表示:20-2-0-3-6。(即紧邻被删除节点的节点打印 0)

但是如果我删除“free(head)”这一行,那么它会打印:20-2-7-3-6(正确)。

请帮忙解释一下原因。

PS:删除头节点或尾节点时没有问题。但是中间的任何其他节点在下一个节点中显示 0。

最佳答案

这是代码的空运行:

20 --> 2 --> 19 --> 7 --> 3 --> 6
^
head

while(position--) // position == 2
{
if(!position) // position == 1, condition is false
head->next = head->next->next;
head = head->next;
}

20 --> 2 --> 19 --> 7 --> 3 --> 6
^
head

while(position--) // position == 1
{
if(!position) // position == 0, condition is true
head->next = head->next->next;
head = head->next;
}

/-----\
20 --> 2 --/ 19 --> 7 --> 3 --> 6 // 2's next is pointing to 7 now
^
head

现在 free(head) 将被执行,这将删除包含数字 7 的节点。现在,当您打印时,您可能会得到:

20 -> 2 -> (reference to deleted node) -> 3 -> 6

我认为这是未定义的行为,您正在引用已删除的节点并打印 0

关于c - 链表删除节点。 Free(pointer) 在下一个节点打印 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com