以下是我的功能:

void deleteAtPointer(struct node **toDel)
{
    printf("\ndeleteAtPointer");

    struct node *temp=NULL;
    temp=(*toDel)->next;

    //(*toDel)=temp->next;
    //free(temp);
    (*toDel)->next=temp->next;
    (*toDel)->data=temp->data;
    //(*toDel)=temp; //If I uncomment this line and comment the above two lines, the node doesn't get deleted. Why?
    free(temp);
}

为什么赋值运算符不将指针temp赋给(*toDel),而如果我逐个赋给它的每个内容,它就会工作。
节点结构有一个int类型成员和一个自引用指针。

最佳答案

我想我明白了。如果使用注释代码,将发生以下情况:

temp = (*toDel)->next;

┌───┐    ┌───┐    ┌───┐    ┌───┐
│ A │ →  │ B │ →  │ C │ →  │ D │
└───┘    └───┘    └───┘    └───┘
           ↑        ↑
           toDel    temp

(*toDel) = temp->next;

┌───┐    ┌───┐    ┌───┐    ┌───┐
│ A │ →  │ B │ →  │ C │ →  │ D │
└───┘    └───┘    └───┘    └───┘
                    ↑        ↑
                    temp     toDel

free(temp);

┌───┐    ┌───┐    ╔═══╗    ┌───┐
│ A │ →  │ B │ →  ║XXX║ →  │ D │
└───┘    └───┘    ╚═══╝    └───┘
                    ↑        ↑
                    temp     toDel

(*toDel) = temp;

┌───┐    ┌───┐    ╔═══╗    ┌───┐
│ A │ →  │ B │ →  ║XXX║ →  │ D │
└───┘    └───┘    ╚═══╝    └───┘
                    ↑
                    toDel / temp

节点已失效,但toDel仍指向它。相当危险。
未注释的代码是正确的代码(不要忘记NULL测试):
void deleteAtPointer (struct node ** toDel)
{
    if (toDel == NULL ││ *toDel == NULL)
        return ;

    struct node * temp = (*toDel)->next;

    if (temp)
    {
        (*toDel)->data = temp->data;
        (*toDel)->next = temp->next;
        free(temp);
    }
    else
    {
        free(*toDel);
        *toDel = NULL;
    }
}

(*toDel)->data = temp->data;

┌───┐    ┌───┐    ┌───┐    ┌───┐
│ A │ →  │ C │ →  │ C │ →  │ D │
└───┘    └───┘    └───┘    └───┘
           ↑        ↑
           toDel    temp

(*toDel)->next = temp->next;

                ┌───────┐
┌───┐    ┌───┐  │ ┌───┐ │   ┌───┐
│ A │ →  │ C │ ─┘ │ C │ └─> │ D │
└───┘    └───┘    └───┘     └───┘
           ↑        ↑
           toDel    temp

free(temp);

                ┌───────┐
┌───┐    ┌───┐  │ ╔═══╗ │   ┌───┐
│ A │ →  │ C │ ─┘ ║XXX║ └─> │ D │
└───┘    └───┘    ╚═══╝     └───┘
           ↑        ↑
           toDel    temp

关于c - 当给出指向节点的指针时,删除单链表中的节点。分配指针不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25171771/

10-11 22:32
查看更多