C 链表删除节点。空闲(指针)在下一个节点中打印0
下面是链接列表代码中的删除节点,它将头指针和要删除的位置作为参数(链接列表中的位置索引从零开始)。删除后,返回指向head的指针C 链表删除节点。空闲(指针)在下一个节点中打印0,c,pointers,nodes,singly-linked-list,C,Pointers,Nodes,Singly Linked List,下面是链接列表代码中的删除节点,它将头指针和要删除的位置作为参数(链接列表中的位置索引从零开始)。删除后,返回指向head的指针 Node* delete(Node* head, int position) { Node *p = head; if(!position) { p = p->next; } else { while(position--) { if(!po
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++相关的,因为在C++中你不能声明一个名为“代码>删除<代码>的函数,所以它不能是C++。一个钢笔或一个铅笔和一个纸是写和调试指针相关代码的最好工具。谢谢。我当时刚开始编码,在问这个问题时是个傻瓜:)。对不起,迟了答复。再次感谢!