c - 在 C 中删除节点

标签 c

所以我正在尝试编写一个方法来删除一个节点和所有附加到它的节点,但我不知道该怎么做。我知道free方法释放使用的内存,而我在创建节点时,使用了malloc。我不确定为什么 free 没有删除节点,我应该怎么做。

struct node {
        char *data;
        struct node *left;
        struct node *right;
}*child = NULL;

    void delete(node* root){
        char array[13];
        node *toDelete;
        //takes in name of node to be deleted
        //scan method to find the node to delete and deletes all of the children of the node first before deleting
        printf ("Please specify a name to delete\n");
        scanf("%s", array);
        toDelete = scan(root, array); //return which node to delete
        removeChild(&toDelete);  //helper method here to go through and delete each children
        if(toDelete == NULL) {
                printf("ERROR -- Node does not exist");
        }
}


void removeChild(node **trash){
        if((*trash)->left == NULL && (*trash)->right == NULL) { //no parents
                free(trash);
                *trash = NULL;
        }
        else if((*trash)->left == NULL && (*trash)->right != NULL) { //have mother
                removeChild((*trash)->right);
        }
        else if((*trash)->left != NULL && (*trash)->right == NULL) { //have father
                removeChild((*trash)->left);
        } else{  //have both
                removeChild((*trash)->left);
                removeChild((*trash)->right);
        }
}

最佳答案

我没有仔细查看你的代码,但我看到了这个并没有按照你的想法去做:

void removeChild(node * trash){
    if(trash->left == NULL && trash->right == NULL) { //no parents
            free(trash);
            trash = NULL;
    }
 ...

打算清除指针的最后一条语句只针对参数执行此操作。调用者的指针(传递给 removeChild())的指针没有为 NULL。这是因为传递给函数的参数被复制了。它们不是通过引用传递的。

推测其他代码可能取决于指针被清除,因此这不能满足它。

关于c - 在 C 中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877959/

相关文章:

将 `ip tuntap add` system() 调用转换为 C 代码

c - malloc 之后出现段错误 char**

c - 复合文字在c99中有什么方法可以变长吗?

c - C 中的变量是否类似于汇编中的标签?

c - 结构链表 - 如何编辑数据

Java Native Access 的 Java 类型映射

在共享内存中创建一个二维数组

c - 如何在 MinTTY 下关闭 echo ?

c++ - 如何在 Igraph + C 中保留节点的位置和名称

c - C中的反向链表程序