数据结构与算法 ~ 图 ~ 图的表示和存储 ~ 邻接多重表
/* graph-Adjacency MultiList */
#include<stdlib.h>
#include<stdio.h>
#define MAX 20
struct EBox{
int ivex,jvex; /*边所依附的两个顶点位置*/
struct EBox *ilink , *jlink;/*分别指向依附这两个顶点的下一条边*/
};
struct VexBox{
int data;
struct EBox *firstedge;/*指向第一条依附该顶点的边*/
};
struct VexBox head[MAX];
int length=-1;
void create_graph(struct VexBox * head){
int i,j;
int source,destination;
struct EBox *newNode,*pointer,*pre;
for(i=0;i<MAX;++i){
head[i].data=i;
head[i].firstedge=NULL;
}
while(1){
printf("\n请输入弧的起点(Exit for -1):");
scanf("%d",&source);
if (source==-1)
break;
printf("\n请输入弧的终点:");
scanf("%d",&destination);
newNode=(struct EBox*)malloc(sizeof(struct EBox));
if (newNode!=NULL){
newNode->ivex=source;/*边结点初始化*/
newNode->jvex=destination;
newNode->ilink=NULL;
newNode->jlink=NULL;
pointer=head[source].firstedge ;
/*pointer指向第一条依附该顶点的边结点*/
while(pointer!=NULL){
pre=pointer;
if (pointer->ivex==source)
pointer=pointer->ilink;
else if (pointer->jvex==source)
pointer=pointer->jlink;
}/*while*/
/*如果没有依附该顶点的边结点*/
if (head[source].firstedge==NULL)
head[source].firstedge=newNode;/*直接插入*/
else {
if (pre->ivex==source)
pre->ilink=newNode;/*否则,依据顶点选择链接点*/
else
pre->jlink=newNode;
}
pointer=head[destination].firstedge ;
while(pointer!=NULL){
pre=pointer;
if (pointer->ivex==destination)
pointer=pointer->ilink;
else if (pointer->jvex==destination)
pointer=pointer->jlink;
}/*while*/
if (head[destination].firstedge==NULL)
head[destination].firstedge=newNode;
else {
if (pre->ivex==destination)
pre->ilink=newNode;
else pre->jlink=newNode;
}
if (source>=destination) j=source;
else j=destination;
if (length<j) { length =j;}
}/*if*/
else {
printf("空间满了!");
exit(0);
}/*if-else*/
}/*while*/
}/*create_graph*/
void Print(struct VexBox *head){
int i,j,data;
struct EBox *pointer;
printf("\n====当前的图是====\n");
for (i=0;i<=length;++i)
{
printf( " head[%d] -ivex- : ",i);
pointer=head[i].firstedge;
data=head[i].data;
while (pointer!=NULL)
{ printf("[%d,%d] ", pointer->ivex,pointer->jvex);
if (pointer->ivex==data) pointer=pointer->ilink;
else if (pointer->jvex==data) pointer=pointer->jlink;
}/*while*/
printf("\n");
}/*for*/
printf("\n===图的输出结束===\n");
}/*Print*/
int main(){
create_graph(head);
Print(head);
system("pause");
exit(0);
}
运行结果:
请输入弧的起点(Exit for -1):1
请输入弧的终点:2
请输入弧的起点(Exit for -1):1
请输入弧的终点:3
请输入弧的起点(Exit for -1):2
请输入弧的终点:4
请输入弧的起点(Exit for -1):2
请输入弧的终点:3
请输入弧的起点(Exit for -1):4
请输入弧的终点:3
请输入弧的起点(Exit for -1):4
请输入弧的终点:5
请输入弧的起点(Exit for -1):5
请输入弧的终点:2
请输入弧的起点(Exit for -1):5
请输入弧的终点:3
请输入弧的起点(Exit for -1):-1
====当前的图是====
head[0] -ivex- :
head[1] -ivex- : [1,2] [1,3]
head[2] -ivex- : [1,2] [2,4] [2,3] [5,2]
head[3] -ivex- : [1,3] [2,3] [4,3] [5,3]
head[4] -ivex- : [2,4] [4,3] [4,5]
head[5] -ivex- : [4,5] [5,2] [5,3]
===图的输出结束===
请按任意键继续. . .