我正在编写一个家谱程序,但我无法从家谱中删除一个节点。我有一个 delete
方法,它获取要删除的节点的名称,找到它,然后将其删除。我释放了 trash
节点,我试图删除的节点,并将其设置为 NULL
,但在我测试它时它仍然存在。我是否应该为节点分配新的左右路径而不是尝试将其设置为 NULL
?
struct node {
char *data;
struct node *left;
struct node *right;
}*child;
void delete(node* root){
char array[13];
node *toDelete;
printf ("Please specify a name to delete\n");
scanf("%s", array);
toDelete = scan(root, array);
if(toDelete == NULL) {
printf("ERROR -- Node does not exist");
} else {
removeChild(&toDelete);
}
}
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);
}
}
最佳答案
对不起。
无论如何,
// free a node and all its children.
// Return # of nodes freed.
int free_node_recursive(node * n){
int total_freed = 1;
// free the left child (if any)
if(n->left != NULL){
free_node_data(n->left);
total_freed += free_node_recursive(n->left);
n->left = NULL;
}
// free the right child (if any)
if(n->right != NULL){
free_node_data(n->right);
total_freed += free_node_recursive(n->right);
n->right = NULL;
}
// actually free the thing.
free(n);
return total_freed;
}
例如。
void delete(node* root){
char array[13];
node *toDelete;
printf ("Please specify a name to delete\n");
scanf("%s", array);
toDelete = scan(root, array);
if(toDelete == NULL) {
printf("ERROR -- Node does not exist");
} else {
free_node_recursive(&toDelete);
}
}
您的问题是,在全局树 (root
) 中,对刚刚删除的节点的引用将仍然存在。沿着树向下的解析器会发现父级中的引用仍然完好无损,并尝试下降到它,发现数据已经空闲
并且不可访问;段错误。
关于c - C语言的家谱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655746/