首页 文章

链接列表删除节点 . Free(指针)在下一个节点中打印0

提问于
浏览
0

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

1 回答

  • 2

    这是代码的干运行:

    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 .

相关问题