二叉树的遍历
#include “stdio.h”
#include “stdlib.h”
#define maxsize 100
typedef struct bitnode
{
int data;
struct bitnode *lchild,*rchild;
}bitnode,*lnode;
lnode chushihua(lnode d[maxsize])
{
d[maxsize]=(lnode)malloc(sizeof(bitnode));
d[maxsize]->data=9;
d[maxsize]->lchild=NULL;
d[maxsize]->rchild=NULL;
return d[maxsize];
}
lnode jianli(lnode d[maxsize],lnode t)
{
lnode p;
int i=1,x;
while(i)
{
scanf("%d%d",&i,&x);
p=(lnode)malloc(sizeof(bitnode));
p->data=x;
p->lchild=NULL;
p->rchild=NULL;
d[i]=p;
if(i1)
t=p;
else
if((i%2)0)
d[i/2]->lchild=p;
else
d[i/2]->rchild=p;
}
return t;
}
void bianli(lnode t)
{
if(t)
{
printf("%d",t->data);
bianli(t->lchild);
bianli(t->rchild);
}
}
void main()
{
lnode t,d[maxsize];
d[maxsize]=chushihua(d);
t=jianli(d,t);
bianli(t);
}
数组建立图
#include “stdio.h”
#define maxsize 4
typedef enum{dg,dn,udn,udg}graphkind;//0 1 2 3
typedef struct{
char vexs[maxsize];
int arcs[maxsize][maxsize];
int vexnum,arcnum;//顶点个数和弧数
graphkind kind;
}mgraph;
void chushihua(mgraph *l)
{
int i;
printf(“请输入顶点个数”);
scanf("%d",&l->vexnum);
printf(“请输入弧数”);
scanf("%d",&l->arcnum);
l->kind=udn;
printf(“请输入顶点元素”);
for(i=0;ivexnum+1;i++)
scanf("%c",&l->vexs[i]);
}
void bianguanxi(mgraph *l)
{
int i=0,j=0,a,b,c=0;
for(i=0;iarcnum;i++)
for(j=0;jarcnum;j++)
l->arcs[i][j]=0;
printf(“输入%d组有关系的元素的数组下标”,l->arcnum);
for(i=1;i<=l->arcnum;i++)
{
scanf("%d%d",&a,&b);
l->arcs[a][b]=1;
l->arcs[b][a]=1;
}
printf(“输出关系矩阵\n”);
for(i=0;iarcnum;i++)
for(j=0;jarcnum;j++)
{
printf("%d",l->arcs[i][j]);
if(j%30&&j!=0)
printf("\n");
}
}
void main()
{
mgraph l;
chushihua(&l);
bianguanxi(&l);
}
图的遍历
#include “stdio.h”
#include “stdlib.h”
#define maxsize 5
typedef enum{dg,dnm,udg,udn}graphkind;//有向图有向往无向图勿相忘
typedef struct arcnode
{
char adjvex;//该户所指向的顶点位置
struct arcnode *nextarc;//指向下一条胡的指针
}arcnode;
typedef struct vnode
{
char vertx;//定点信息
arcnode *firstarc;//指向第一条已衣服顶点的指针
int f;//方便遍历
}adjlist;
typedef struct
{
adjlist b[maxsize];
int vex,arc;//顶点数和弧数
graphkind kind;
}algraph;
void chushihua(algraph *p)
{
Int i;
printf(“请输入顶点数和弧数\n”);
scanf("%d%d",&p->vex,&p->arc);
printf(“请输入顶点\n”);
for(i=0;iarc+1;i++)
{
scanf("%c",&p->b[i].vertx);
p->b[i].firstarc=NULL;
p->b[i].f=0;
}
for(i=1;i<=p->arc;i++)
printf("%c",p->b[i].vertx);
p->kind=udg;
}
void creat(algraph *p,arcnode l)
{
int i=1,k,j;
printf(“请输入与该顶点有关系的下标”);
while(i<=p->arc)
{
i++;
l=(arcnode)malloc(sizeof(arcnode));
scanf("%d%d",&k,&j);
l->adjvex=j;
l->nextarc=p->b[k].firstarc;
p->b[k].firstarc=l;
}
}
void dfs(algraph *p,int v)
{
int i;
arcnode *l;
if(p->b[v].f0)
printf("%c",p->b[v].vertx);
p->b[v].f=1;
l=p->b[v].firstarc;
i=p->b[l->adjvex].f;
while(i0)
{
dfs(p,l->adjvex);
l=l->nextarc;
}
}
void bianli(algraph *p)
{
int v;
for(v=1;v<=p->vex;v++)
{
if(p->b[v].f0)
dfs(p,v);
}
}
void main()
{
int v;
arcnode l;
algraph p;
chushihua(&p);
creat(&p,&l);
bianli(&p);
}
相关文章
- 11-22对应每一章的数据结构代码6