【问题标题】:Linked list delete node. Free(pointer) prints 0 in next node链表删除节点。 Free(pointer) 在下一个节点打印 0
【发布时间】:2018-11-15 20:25:34
【问题描述】:

下面是 Linklist 代码中的一个删除节点,它将头指针和要删除的位置作为参数(位置索引在 Linklist 中从零开始)。并且删除后返回一个指向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。

【问题讨论】:

  • 您是否尝试使用调试器单步执行您的代码?旁注:这个问题与 C++ 有什么关系,因为在 C++ 中你不能声明一个名为 delete 的函数,所以它不能是 C++。
  • 一支钢笔或铅笔和一张纸是编写和调试指针相关代码的最佳工具。

标签: c pointers nodes singly-linked-list


【解决方案1】:

这是代码的试运行:

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

【讨论】:

  • 谢谢。当时刚开始编码,在问这个问题时还是个菜鸟:)。抱歉回复晚了。再次感谢!
猜你喜欢
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2023-02-25
  • 2011-06-06
相关资源
最近更新 更多