链表删除节点。 Free(pointer) 在下一个节点打印 0
Linked list delete node. Free(pointer) prints 0 in next node
下面是链表代码中的一个删除节点,它以头指针和要删除的位置作为参数(链表中的位置索引从零开始)。删除后,returns 一个指向 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
。
下面是链表代码中的一个删除节点,它以头指针和要删除的位置作为参数(链表中的位置索引从零开始)。删除后,returns 一个指向 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
。