莁/*膈 数据结构C语言版树的双亲表存储表示袆 P135螂 编译环境:Dev-C++ 日期:2011年2月13日蚈*/蚇袄#include<>袁肇typedefcharTElemType;莇蚁//树的双亲表存储表示羀#defineMAX_TREE_SIZE100蒆膇typedefstruct蚃{莂 TElemTypedata; //数据域膀 intparent; //双亲位置域薄}PTNode; //结点结构螄蒀typedefstruct蕿{莄 PTNodenodes[MAX_TREE_SIZE]; //存储结点的数组薁 intn;//结点数蕿}PTree;聿肅typedefstruct薃{羁 intnum;蒈 TElemTypename;袅}QElemType;//定义队列元素类型蚄肀typedefstructQNode袇{薅 QElemTypedata; //数据域蒁 structQNode*next; //指针域蒂}QNode,*QueuePtr;莇芆typedefstruct蒃{薀 QueuePtrfront,//队头指针,指针域指向队头元素羀 rear;//队尾指针,指向队尾元素肆}LinkQueue;薄虿TElemTypeNil='';//以空格符为空葿螆intInitTree(PTree*T)莂{//操作结果:构造空树T羁 (*T).n=0;衿 return1;薇}蒃腿voidDestroyTree()芈{芇 //由于PTree是定长类型,无法销毁蒄}蒂螈//构造一个空队列Q肈intInitQueue(LinkQueue*Q)节{薀 (*Q).front=(*Q).rear=(QueuePtr)malloc(sizeof(QNode)); //动态分配一个空间膇 if(!(*Q).front)蒄 exit(0);莃 (*Q).front->next=NULL; //队头指针指向空,无数据域,这样构成了一个空队列蝿 return1;薆}芄莅//若Q为空队列,则返回1,否则返回0肁intQueueEmpty(LinkQueueQ)芀{羅 if(==)膂 return1;腿 else虿 return0;螅}芃薂//插入元素e为Q的新的队尾元素膈intEnQueue(LinkQueue*Q,QElemTypee)蒅{芅 QueuePtrp=(QueuePtr)malloc(sizeof(QNode));蚀 if(!p)//存储分配失败薈 exit(0);芆 //生成一个以为e为数据域的队列元素肂 p->data=e;肂 p->next=NULL;羇 //将该新队列元素接在队尾的后面羆 (*Q).rear->next=p;膃 (*Q).rear=p;膁 return1;莇}螇芅//若队列不空,删除Q的队头元素,用e返回其值,并返回1,否则返回0艿intDeQueue(LinkQueue*Q,QElemType*e)肀{蒇 QueuePtrp;肂 if((*Q).front==(*Q).rear)蚂 return0;蕿 p=(*Q).front->next; //队头元素膇 *e=p->data;肄 (*Q).front->next=p->next;螀 if((*Q).rear==p)罿(*Q).rear=(*Q).front;蚄 free(p);膅 return1;膂}莈蒄//构造树T羂intCreateTree(PTree*T)芁{螇 LinkQueueq;膄 QElemTypep,qq;羄 inti=1,j,l;荿 charc[MAX_TREE_SIZE];//临时存放孩子结点数组芇 袅 InitQueue(&q);//初始化队列肅 printf("请输入根结点(字符型,空格为空):");螁 scanf("%c%*c",&(*T).nodes[0].data);//根结点序号为0,%*c吃掉回车符蚆 if((*T).nodes[0].data!=Nil)//非空树蚅 {袂(*T).nodes[0].parent=-1;//根结点无双亲袀 =(*T).nodes[0].data;莀 =0;莆 EnQueue(&q,qq);//入队此结点袄 while(i<MAX_TREE_SIZE&&!QueueEmpty(q))//数组未满且队不空节{蝿 DeQueue(&q,&qq);//出队一个结点膆 printf("请按长幼顺序输入结点%c的所有孩子:",);蚁 gets(c);莁 l=strlen(c);膈 for(j=0;j<l;j++)袆{螂(*T).nodes[i].data=c[j];葿(*T).nodes[i].paren
数据结构C语言版 树的双亲表存储表示 来自淘豆网m.daumloan.com转载请标明出处.