我正在尝试编写一个方法,用于删除一个节点及其所有附加的节点,但是我对该怎么做感到困惑。我知道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);
}
}
scanf
的返回值,并将存储的字符限制为12
,例如if (scanf ("%12s", array) != 1) { /* 处理错误 */ }
。此外,你还应该删除stdin
中剩余的任何字符(否则它们将被视为下一个输入)。 - David C. Rankin