#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20
typedef int Status;
typedef struct ArcBox{
int tailvex,headvex;//该弧的尾和头的顶点的位置
struct ArcBox *hlink,*tlink; //指向弧头相同和弧尾相同节点的指针
}ArcBox; //用来存储弧信息的各个节点
typedef struct VexNode{
char data; //头结点的节点的名字
ArcBox *firstin,*firstout;//指向第一条入狐和出弧的指针
}VexNode; //用来存储头结点
typedef struct{
VexNode xlist[MAX_VERTEX_NUM];//来存储头结点的数组
int vexum,arcnum;//当前顶点数和弧数
}OLGraph;//主结构体
Status LocateVex(OLGraph &g,char c)//查找函数,查找c在图中存储位置,返回位置
{
int i;
for(i=0;i<g.vexum;i++)
{
if(g.xlist[i].data==c)
break;
}
return i;
}
Status createDG(OLGraph &g)//创建图
{
char ch1,ch2,ch3,node1,node2;
int i,j,a,b;
ArcBox *p;
printf("请输入图的节点的个数和弧的个数");
scanf("%d",&ch1);
getchar();
scanf("%d",&ch2);
getchar();
g.vexum=ch1;
g.arcnum=ch2;
printf("请输入表头节点:");
for(i=0;i<g.vexum;i++)//初始化图
{
ch3=getchar();
getchar();
g.xlist[i].data=ch3;
g.xlist[i].firstin=NULL;
g.xlist[i].firstout=NULL;
}
for(j=0;j<g.arcnum;j++)
{
printf("输入一条弧的起点和他的终点");
node1=getchar();
getchar();
node2=getchar();
getchar();
a=LocateVex(g,node1); b=LocateVex(g,node2);//查找出节点在图中的存储位置
p=(ArcBox*)malloc(sizeof(ArcBox));
p->headvex=a;
p->tailvex=b;
p->hlink=g.xlist[b].firstin;//把处于弧尾节点的第一个入狐节点赋给弧头相同的指针域
p->tlink=g.xlist[a].firstout;//把处于弧头节点的第一个出弧节点赋给弧尾相同的指针域
g.xlist[b].firstin=g.xlist[a].firstout=p;//再把p节点和头节点相连
//上几步就是链表的普通插入节点算法
}
return 1;
}
Status show(OLGraph &g)//查询
{
int i ;
ArcBox *p;
for(i=0;i<g.vexum;i++)
{
printf("顶点%c的出度为:",g.xlist[i].data);
p=g.xlist[i].firstout;
while(p)
{
printf("%c",g.xlist[p->tailvex].data);
p=p->tlink;
}
printf("入度为:");
p=g.xlist[i].firstin;
while(p)
{
printf("%c",g.xlist[p->headvex].data );
p=p->hlink;
}
printf("\n");
}
return 1;
}
void main()
{
OLGraph g;
int j,i;
createDG(g);
show(g);
getchar();
}
图算法-----图的十字链表表示法
最新推荐文章于 2024-08-01 10:12:30 发布