所以我正在尝试编写一个方法来删除一个节点和所有附加到它的节点,但我不知道该怎么做。我知道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/