我编写了一个二叉搜索树,并创建了一个删除节点的函数。 通常它有两个输入参数,第一个是指向需要删除的对象的指针,第二个指向二叉搜索树根。如何设置指针无效?
基本上,我所有的情况下工作,除了“最简单”的节点是叶。
我的代码将应该删除的节点的内容设置为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;
}
Basicly我“只”需要告诉指针* 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);
}
}
但即时segfaulting,也许某处可以看到哪里,因为在我看来这个解决方案应该工作。
是否有原因将指针设置为NULL不是一个可行的选项?但是,也许你正在看着这个错误的方式。通常,当维护这样的树时,您将设置左右节点的指针,以便它们不再引用已删除的节点。 –
是不是忘记了对“p”的引用? –
0XDEADBEEF有时用于标记指针无效 – monkeyStix