我在二进制搜索树中有一个删除节点功能,如下所示:

struct Node *_removeNode(struct Node *curr, TYPE val) {
    /* FIX ME */
    printf("curr->val: %.1f...%p\t val: %.1f\n", curr->val, curr, val);
    struct Node* to_del = NULL;

    if(val < curr->val){

            return _removeNode(curr->left, val);

    } else if( val > curr->val) {

            return _removeNode(curr->right, val);

    } else {

        //case 1 -> curr is a leaf
        if(curr->left == NULL && curr->right == NULL){
            printf("removed %.1f\n", curr->val);
            to_del = curr;
            free(to_del);

        }

        //case if left node is not null but right is
        if(curr->left != NULL && curr->right == NULL){
            to_del = curr;
            printf("to_del: %p...%.1f\t", to_del, to_del->val);
            curr = curr->left;
            printf("new curr: %p...%.1f\n", curr, curr->val);
            free(to_del);

        }

        //case if right node is not null but left is
        if(curr->left == NULL && curr->right != NULL){
            to_del = curr;
            printf("to_del: %p...%.1f\t", to_del, to_del->val);
            curr = curr->right;
            printf("new curr: %p...%.1f\n", curr, curr->val);
            free(to_del);
        }

        //case both are not not null
        if(curr->left != NULL && curr->right != NULL){
            to_del = curr;
            printf("to_del: %p...%.1f\t", to_del, to_del->val);
            curr->right->left = curr->left;
            curr = curr->right;
            printf("new curr: %p...%.1f\n", curr, curr->val);
            free(to_del);
        }


    }

    to_del = NULL;
    return to_del;

}


该代码应该返回指向NULL的指针以通过测试用例,但是我尝试的所有操作都会引发内存错误。有没有一种方法可以将结构设置为NULL然后返回它?

最佳答案

看着:

    if(curr->left == NULL && curr->right == NULL){
        to_del = curr;
        free(to_del);
    }
    if(curr->left != NULL && curr->right == NULL){


如果第一个if为true,则将释放curr指向的内存。当您在第二个if curr->left中执行操作时,您将收到一个错误消息,因为不再有->left

也许您应该使用else if

关于c - 释放结构指针,然后将其设置为null,然后返回引发错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33598205/

10-13 05:29