数据结构与算法~图~图的表示和存储~邻接表
#include<stdlib.h>
#include<stdio.h>
#define MAX 20
struct ArcNode{ /*弧结点信息*/
int adjvex; /*该弧所指向的顶点的信息*/
struct ArcNode *nextarc; /*指向下一条弧的指针*/
};
struct VexNode{
int data; /*顶点信息*/
struct ArcNode *firstarc;/*指向第一条依附于该顶点的弧的指针*/
};
struct VexNode head[MAX]; /*顶点数组*/
int vexnum=-1;
int graphtype;
int formatlist(){
printf("\n1---创建无向图:");
printf("\n2---创建有向图:");
printf("\n0---退出");
printf("\n输入你的选择:");
scanf("%d",&graphtype);
return graphtype;
}
void constr(struct VexNode *head,int source, int destination){
int max;
struct ArcNode *newNode,*pointer;
newNode=(struct ArcNode*)malloc(sizeof(struct ArcNode));/*分配空间*/
if (newNode==NULL){
printf("输入错误!");
exit(0);
}else{
newNode->adjvex=destination; /*生成弧结点*/
newNode->nextarc=NULL;
if ( head[source].firstarc==NULL) /*头结点没有邻接点*/
head[source].firstarc=newNode;
else{
pointer=head[source].firstarc ; /*头结点已有邻接点*/
while ((pointer->adjvex!=destination)&&(pointer->nextarc!=NULL) )
pointer=pointer->nextarc; /*找到最后一个邻接点*/
if (pointer->adjvex==destination){
printf("\n输入重复!");
free(newNode);
}else{
pointer->nextarc=newNode;/*接入*/
max=(source>destination)?source:destination; /*确定顶点的最大值*/
if (vexnum<max) vexnum=max;
}/*else*/
}/*ifelse*/
}/*ifelse*/
}/*constr*/
void create_graph(struct VexNode *head){
int i,max,cost;
int source,destination;
struct ArcNode *newNode,*pointer;
for(i=1;i<MAX;++i){
head[i].data=i;
head[i].firstarc=NULL;
}
while(1){
printf("\n请输入弧信息(起点 终点 退出输入-1):");
scanf("%d%d",&source,&destination,&cost);
if (source==-1) break;
if (source==destination)
printf("\n 起点和终点相同!");
else{
constr(head,source,destination);
if (graphtype==1) constr(head,destination,source);
}
}/*while*/
}/*create_graph*/
void Print(struct VexNode * head){
int i,j;
struct ArcNode *pointer;
printf("\n=====当前图是=====\n");
for (i=1;i<=vexnum;++i){
printf( " head[%d]: ",i);
pointer=head[i].firstarc ;
while (pointer!=NULL){
printf("[%d]=>", pointer->adjvex);
pointer=pointer->nextarc;
}/*while*/
printf("\n");
}/*for*/
printf("\n===图的输出结束===\n");
}/*Print*/
int main(){
int answer,search;
printf("\n=============================");
printf("\n 图--邻接表 " );
printf("\n============================\n");
answer=formatlist();
switch(answer){
case 1:
case 2: create_graph(head);break;
case 0: exit(0);
default:{ printf("\n你的选择错误,请重新选择.\n");
answer=formatlist();}
}/*switch*/
Print(head);
system("pause");
exit(0);
}
运行结果:
=============================
图--邻接表
============================
1---创建无向图:
2---创建有向图:
0---退出
输入你的选择:2
请输入弧信息(起点 终点 退出输入-1):1 3
请输入弧信息(起点 终点 退出输入-1):1 2
请输入弧信息(起点 终点 退出输入-1):2 3
请输入弧信息(起点 终点 退出输入-1):2 4
请输入弧信息(起点 终点 退出输入-1):4 3
请输入弧信息(起点 终点 退出输入-1):4 5
请输入弧信息(起点 终点 退出输入-1):5 2
请输入弧信息(起点 终点 退出输入-1):5 3
请输入弧信息(起点 终点 退出输入-1):-1 -1
=====当前图是=====
head[1]: [3]=>[2]=>
head[2]: [3]=>[4]=>
head[3]:
head[4]: [3]=>[5]=>
head[5]: [2]=>[3]=>
===图的输出结束===
请按任意键继续. . .