c - 如何设置指针无效?

标签 c pointers binary-search-tree nodes

我编写了一个二叉搜索树并创建了一个删除节点的函数。 一般有两个输入参数,第一个是指向需要删除的对象的指针,第二个是指向二叉搜索树的根。

基本上我所有的情况都有效,除了节点是叶子的“最简单”的情况之外。

我的代码将应该删除的节点的内容设置为 0,但是仍然存在对此的引用,并且它显示在树中。

*p 是应该被删除的元素。

*pBaum 指向树的根。

*p->right 和 *p->left 是指向 *p 的右子树和左子树的指针。

*p->conten 是 *p 的值。

我在叶案例中的代码:

struct tnode  *deletenode(struct tnode *p, struct tnode *pBaum) 
{
    if (p !=NULL)
    {

        if ((p->left == NULL) && (p->right == NULL)) 
        {
        printf("%d Ist Blatt \n", p->content);
        free(p);
        return pBaum;
        }

基本上我“只”需要告诉指针 *p 从现在开始它是无效的。但是我无法找到合适的解决方案。也许你们可以帮忙。

编辑:好的,我已经尝试过将父指针设置为 NULL。

struct tnode* danglingPointerFix (struct tnode *p, int nodtodelete)
{
 if((p->right)->content = nodtodelete)
    {
        p->right = NULL;
        return 0;
    }
    if((p->left)->content = nodtodelete)
    {
        p->left = NULL;
        return 0;
    }
}

struct tnode *searchnode(struct tnode *p, int nodtodelete) 
{
if (p == NULL)
{
    printf("Baum ist leer oder Element nicht vorhanden \n");
    return 0;
}
if ( p -> content == nodtodelete)
{
    return p;
}
if (p->content < nodtodelete)
{
    danglingPointerFix(p, nodtodelete);
    return searchnode (p->right, nodtodelete);
}
if (p->content > nodtodelete)
{
    danglingPointerFix(p, nodtodelete);
    return searchnode(p->left, nodtodelete);
}
}

但是我存在段错误,也许某个地方可以看到哪里,因为在我看来这个解决方案应该有效。

最佳答案

虽然你已经释放了叶子节点,但父节点仍然保留着悬空指针。

解决这个问题的一种方法是添加以下函数:

struct tnode  *deleteLeftNode(struct tnode *parent, struct tnode *pBaum) {

    if (parent) {
        deletenode(parent->left, pBaum);
        parent->left = NULL;
    }
    return pBaum;
}

struct tnode  *deleteRightNode(struct tnode *parent, struct tnode *pBaum) {

    if (parent) {
        deletenode(parent->right, pBaum);
        parent->right = NULL;
    }
    return pBaum;
}

关于c - 如何设置指针无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38590487/

相关文章:

c - 一次在一个文件中写入一个结构

c - 可以用C/SDL写塔防吗

关于指针使用的说明

c - 如何在 C 中访问链表中的下一个元素?

arrays - Fortran:哪种方法可以更快地更改数组的等级? ( reshape 与指针)

java - 在二叉搜索树中的何处添加有效性检查

algorithm - BST :-Given the inorder successor of each node, 在 O(h) 中找到每个节点的父节点

Clang 与 1 优化的倒数

c - linux - 文件系统是否允许产生黑洞?

c - 使用递归函数在二叉搜索树中插入项目