什么是“读取访问违规...是nullptr”?

问题描述 投票:1回答:2

我可以使用一些帮助。我一直试图让我的删除功能正常工作,但不管我似乎做什么它总是给我一个“是nullp”错误。我的代码有点凌乱,因为我一直在恐慌并疯狂地尝试任何想到的东西。如果我需要,我准备重新开始。无论我在哪里寻找有关nullptr的信息都没有真正给出我实际理解的解释。我的理解是当你试图取消引用一个指针/节点时会给出一个“was nullptr”错误,但是我找不到办法处理对我有意义的问题。任何帮助都非常感谢。我的代码是:

 `

BT::BT()
{
    node* root = NULL;
}

char BT::FindReplacement(node* parent, char param)
{
    if (parent == NULL) //In case someone tries to delete a node while there aren't any nodes in the Tree
    {
        return NULL;
    } 

    parent = parent->right;
    while (parent->left != NULL)
    {
        parent = parent->left;
    }

    return parent->data;
}

void BT::leafDriver()
{
    int count = 0;
    leafCount(root, count); 
}

void BT::leafCount(node* start, int count)
{


    if ((start->left == NULL) && (start->right == NULL))
    {
        count++;
    }

    if (start->left != NULL)
    {
        leafCount(start->left, count);
    }

    if(start->right != NULL)
    {
        leafCount(start->right, count);
    }
cout << " There are " << count << " number of leaves in the BST" << endl;

}


void BT::deletionDriver(char param)
{
    deletion(root, param);
}

void BT::deletion(node* parent, char param)
{

    if (parent->data < param) 
    {
        parent->left = parent->left->left;
        deletion(parent -> left, param);
        cout << "checking left node" << endl;
    }

    else if (parent->data > param)
    {
        parent->right = parent->right->right;
        deletion(parent->right, param);
        cout << "checking right node" << endl;
    }

    else if (parent->data == param)
    {
        //Case 1: No Children
        if (parent->left == NULL && parent->right == NULL)
        {
            delete parent;
            parent = NULL;

        }


        //Case 2: One Child
        else if ((parent->right == NULL) && (parent->left != NULL))
        {
            node* temp = parent;
            parent = parent->left;
            delete temp;
        }

        else if (parent->left == NULL)
        {
            node* temp = parent;
            parent - parent->right;
            delete temp;
        }

        //Case 3: Two Children
        else if ((parent->left != NULL) && (parent->right != NULL))
        {
            char tempParam;
            tempParam = FindReplacement(parent, param);
            parent->data = tempParam;
            deletion(parent->right, tempParam);
        }
    }

    else 
        cout << "Item is not found in BST" << endl;
}`
c++ binary-search-tree nullptr
2个回答
0
投票

每当你有这样的代码:

parent = parent->right;

您需要检查新分配给父级的值是否为空。换句话说,您的代码应始终如下所示:

parent = parent->right;
if ( parent == nullptr ) {
    // handle null case
}
else {
    // handle case when there is another node
}

0
投票
while (parent->left != NULL)

改成了

while (parent != NULL)

它应该工作

© www.soinside.com 2019 - 2024. All rights reserved.