森林的边序创建
文章目录
queue.h的引入
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include<string.h>
struct bintreenode;
#define qelemtype bintreenode*
typedef struct qnode
{
qelemtype data;
struct qnode *next;
}qnode,*qlink;
typedef struct
{
qlink front;
qlink rear;
}linkqueue;
void initqueue(linkqueue &q);
int isempty(linkqueue q);
void pushqueue(linkqueue &q,qelemtype e);
void popqueue(linkqueue &q,qelemtype &e);
void initqueue(linkqueue &q)
{
q.front=q.rear=(qlink)malloc(sizeof(qnode));
q.front->next=NULL;
}
void pushqueue(linkqueue &q,qelemtype e)
{
qlink p;
p=(qlink)malloc(sizeof(qnode));
p->data=e;
p->next=NULL;
q.rear->next=p;
q.rear=p;
}
void popqueue(linkqueue &q,qelemtype &e)
{
if(q.front==q.rear)
{
printf("队为空,没有可以删除的");
}
else
{
qlink p=q.front->next;
e=p->data;
q.front->next=p->next;
if(q.rear==p)
q.rear=q.front;
free(p);
}
}
int isempty(linkqueue q)
{
if(q.front==q.rear)
return 1;
else
return 0;
}
实现代码
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include"queue.h"
#define elemtype char
typedef struct bintreenode
{
elemtype data;
bintreenode *firstchild,*nextsibling;
}bintreenode,*binlink;
typedef struct
{
binlink root;
elemtype refvalue;
}forest;
void initforest(forest *bt,elemtype ref);
void createbyedge(forest *bt);
void createbyedge(binlink &t);
void initnode(binlink &t);
void main()
{
forest myforest;
initforest(&myforest,'#');
createbyedge(&myforest);
}
void initforest(forest *bt,elemtype ref)
{
bt->root=NULL;
bt->refvalue=ref;
}
void initnode(binlink &t)
{
t=(binlink)malloc(sizeof(bintreenode));
t->firstchild=t->nextsibling=NULL;
}
void createbyedge(forest *bt)
{
createbyedge(bt->root);
}
void createbyedge(binlink &t)
{
initnode(t);
char f,s;
scanf("%c%c",&f,&s);
linkqueue q;
initqueue(q);
binlink bt,bc;
initnode(bc);
if(f=='#')
{
t->data=s;
pushqueue(q,t);
}
getchar();
scanf("%c%c",&f,&s);
while(!isempty(q))
{
popqueue(q,bt);
if(bt->data==f)
{
bc->data=s;
bt->firstchild=bc;
pushqueue(q,bc);
getchar();
scanf("%c%c",&f,&s);
if(s=='#')
return;
while(bt->data==f)
{
binlink bs;
initnode(bs);
bs->data=s;
bc->nextsibling=bs;
pushqueue(q,bs);
getchar();
scanf("%c%c",&f,&s);
bc=bs;
}
}
}
}