树的孩子双亲表示法

添加链接描述
按照上述博客,测试了一下这个程序.有两点说说明一下.首先,博主说使用C语言,我第一次用.c文件编译,出现error: expected ';', ',' or ')' before '&' token
这是使用了引用&,而在c语言中没有引用的概念,&在C语言中是取地址符号.后期改为.cpp文件即可运行
第二点就是:fflush(stdin)
fflush(stdin)是一个计算机专业术语,功能是清空输入缓冲区,通常是为了确保不影响后面的数据读取(例如在读完一个字符串后紧接着又要读取一个字符,此时应该先执行fflush(stdin);)。因为我需要从输入缓冲区读取一些参数,所以使用这个函数清空缓冲区,防止上一次输入对下一次结果产生影响.
下面是可运行的代码,相应的做一些注释

#include<stdio.h>
#include<stdlib.h>
#define MAXNODE 20
typedef char ElemType;
typedef struct SCNode{//孩子节点
	int childnode;
	struct SCNode *nextchild;
}CNode;
typedef struct {
	ElemType data;
	CNode *firstchild;
	int r;//r指向双亲的序号
	
}CTBox;
typedef struct{
	CTBox tree[MAXNODE];//结点数目
	int n;
}CTree;
void InitCtree(CTree &t){
//初始化树
	int i;
	printf("请输入树的结点个数:\n");
	scanf("%d\n",&t.n);
	printf("依次输入各个结点");
        for(i=0;i<t.n;i++){
	fflush(stdin);
	t.tree[i].data=getchar();
	t.tree[i].r=0;
	t.tree[i].firstchild=NULL;
}
}

void AddChild(CTree &t){
//添加孩子
	int i,j,k;
	printf("添加孩子:\n");
	for(k=0;k<t.n-1;k++){
	fflush(stdin);
	printf("请输入每个孩子结点以及双亲结点的序号");
	scanf("%d%d",&i,&j);
	fflush(stdin);
	CNode *p=(CNode *)malloc(sizeof(CNode));
	p->childnode=i;
	p->nextchild=NULL;
	t.tree[i].r=j;//找到双亲
	//如果双亲没有孩子,那么添加的孩子就是长子
	if(!t.tree[j].firstchild)
		t.tree[j].firstchild=p;
	else{
	//如果双亲有孩子,那么添加的孩子及时nextchild
		CNode *temp=t.tree[j].firstchild;
		while(temp->nextchild)//如果不止一个孩子,那么往后递归 使得p成文最后一个孩子
		temp=temp->nextchild;
		temp->nextchild=p;
}
}
}
void FindChild(CTree &t){
//查找孩子结点
	int i,n;
	printf("\n请输入要查询结点的序号\n");
	scanf("%d",&n);
	if(!t.tree[n].firstchild)//此时结点没有孩子
		printf("结点%c无孩子结点\n",t.tree[n].data);
	else{
		CNode *p=t.tree[n].firstchild;
		printf("%c结点的孩子序号为:\n",t.tree[i].data);
	 while(p){//这是结点不止一个孩子的情况
		printf("%d",p->childnode);
		p=p->nextchild;
}
}
}

void FindParent(CTree &t){
//查找双亲结点
	int i,n;
	printf("请输入要查询的结点的序号\n");
	scanf("%d",&n);
	if(!n)
		printf("结点%c无双亲结点\n",t.tree[n].data);
	else
		printf("结点%c的双亲结点位%c\n",t.tree[n].data,t.tree[t.tree[n].r].data);//最后一个参数是支出双亲的数据

}
	int main(){
	CTree t;
	InitCtree(t);
	AddChild(t);
	FindChild(t);
	return 0;

}

猜你喜欢

转载自blog.csdn.net/Zyong139064359/article/details/89735424