自定义的头文件
typedef struct BiTNode
{
int data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
如下是使用形参是指针的引用的函数,结果是正确的
#include "BiTree.h"
#include "stdlib.h"
#include "stdio.h"
bool Delete(BiTree &p)
{
BiTree q = (BiTree)malloc(sizeof(BiTNode));
q = p;
p = p->lchild;
free(q);
return true;
}
bool DeleteBST(BiTree &T, int key)
{
if (!T)return false;
else if (key==T->data)
{
return Delete(T);
}
else if (key < T->data)
{
return DeleteBST(T->lchild, key);
}
}
int main()
{
BiTree t1 = (BiTree)malloc(sizeof(BiTNode));
BiTree t2 = (BiTree)malloc(sizeof(BiTNode));
BiTree t3 = (BiTree)malloc(sizeof(BiTNode));
t1->data = 3;
t2->data = 2;
t3->data = 1;
t1->lchild = t2;
t1->rchild = NULL;
t2->lchild = t3;
t2->rchild = NULL;
DeleteBST(t1, 2);
printf("%d\n", t1->lchild->data);
system("PAUSE");
return 0;
}
结果
然后如下是形参为指针的,其实函数是一样的,只是形参从上面的接收指针的引用改为了接收指针
#include "BiTree.h"
#include "stdlib.h"
#include "stdio.h"
bool Delete(BiTree p)
{
BiTree q = (BiTree)malloc(sizeof(BiTNode));
q = p;
p = p->lchild;
free(q);
return true;
}
bool DeleteBST(BiTree T, int key)
{
if (!T)return false;
else if (key==T->data)
{
return Delete(T);
}
else if (key < T->data)
{
return DeleteBST(T->lchild, key);
}
}
int main()
{
BiTree t1 = (BiTree)malloc(sizeof(BiTNode));
BiTree t2 = (BiTree)malloc(sizeof(BiTNode));
BiTree t3 = (BiTree)malloc(sizeof(BiTNode));
t1->data = 3;
t2->data = 2;
t3->data = 1;
t1->lchild = t2;
t1->rchild = NULL;
t2->lchild = t3;
t2->rchild = NULL;
DeleteBST(t1, 2);
printf("%d\n", t1->lchild->data);
system("PAUSE");
return 0;
}
结果
结果明显是有问题的,原因应该在free了第2个结点,却没把第一个结点的lchild改为指向第3个结点。可是为什么前一个(即接收指针的引用那个)却没问题呢?两个的区别仅仅在于接收的参数,可是前一个没问题而后一个出了问题。我想不明白前一个为什么会没出问题,求大神指点