/*
*图的邻接表存储
*/
#include<stdio.h>/* EOF(=^Z或F6),NULL */
#include<stdlib.h>
#include<string.h>
#define MAX_VERTEX_NUM 20
//#define MAX_NAME 5
typedef int InfoType ;//存放网的权值
typedef char VertexType[5];//字符串类型
typedef enum
{
DG,DN,UDG,UDN
}GraphKind;
typedef struct ArcNode//表结点
{
int adjvex;//弧所指向顶点的位置
struct ArcNode *nextarc;//指向下条弧的指针
InfoType info;//弧相关信息(权)
}ArcNode;
typedef struct VNode//头结点
{
VertexType data;//顶点信息
ArcNode *firstarc;//第一个表结点的地址,指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct
{
AdjList vertices;
int vexnum,arcnum;//图当前的顶点数和弧数
GraphKind kind;
}ALGraph;
/* 采用邻接表存储结构,构造没有相关信息的图G*/
void InitALGraph(ALGraph *G)
{
printf("请输入图的类型(DG:0,DN:1,UDG:2,UDN:3)");
scanf("%d",&(*G).kind);
printf("请输入图的顶点数:");
scanf("%d",&(*G).vexnum);
printf("请输入图的边数:");
scanf("%d",&(*G).arcnum);
int i;
printf("请输入定点向量:");
for(i=0;i<(*G).vexnum;++i)
{
scanf("%s",(*G).vertices[i].data);
(*G).vertices[i].firstarc=NULL;
}
}
/* 初始条件: 图G存在,u和G中顶点有相同特征 */
/* 操作结果: 若G中存在顶点u,则返回该顶点在图中位置;否则返回-1 */
int getLocateVex(ALGraph G,VertexType u)
{
int i;
for(i=0;i<G.vexnum;++i)
if(strcmp(u,G.vertices[i].data)==0)
return i;
return -1;
}
void createALGraph(ALGraph *G)
{
InitALGraph(G);
VertexType v1,v2;
int i,v1_site,v2_site;
printf("请输入图的弧(形如v1 v2):\n");
for(i=0;i<(*G).arcnum;++i)
{
scanf("%s%s",v1,v2);
v1_site=getLocateVex(*G,v1);//弧尾
v2_site=getLocateVex(*G,v2);//弧头
ArcNode *p1,*p2;
p1=(ArcNode *)malloc(sizeof(ArcNode));
p1->adjvex=v2_site;
p1->info=0;//初始化权值为0
p1->nextarc=(*G).vertices[v1_site].firstarc;
(*G).vertices[v1_site].firstarc=p1;
switch((*G).kind)
{
case DG:
break;
case DN:
printf("请输入权值:");
scanf("%d",&p1->info);
break;
case UDG:
p2=(ArcNode *)malloc(sizeof(ArcNode));
p2->adjvex=v1_site;
p2->info=0;//初始化权值为0
p2->nextarc=(*G).vertices[v2_site].firstarc;
(*G).vertices[v2_site].firstarc=p2;//头插入
break;
case UDN:
printf("请输入权值:");
scanf("%d",&p1->info);
p2=(ArcNode *)malloc(sizeof(ArcNode));
p2->adjvex=v1_site;
p2->info=p1->info;//初始化权值为0
p2->nextarc=(*G).vertices[v2_site].firstarc;
(*G).vertices[v2_site].firstarc=p2;//头插入
break;
default:
exit(0);
}
}
}
void printALGraph(ALGraph G)
{
int i;
for(i=0;i<G.vexnum;++i)
{
ArcNode *p=G.vertices[i].firstarc;
while(p)
{
switch(G.kind)
{
case UDG:
printf("%s --",G.vertices[i].data);
printf("%s",G.vertices[p->adjvex].data);
break;
case UDN:
printf("%s --",G.vertices[i].data);
printf("%s,%d",G.vertices[p->adjvex].data,p->info);
break;
case DG:
printf("<%s->",G.vertices[i].data);
printf("%s>",G.vertices[p->adjvex].data);
break;
case DN:
printf("< %s ->", G.vertices[i].data);
printf(" %s , %d >", G.vertices[p->adjvex].data, p->info);
break;
default:
exit(0);
}
p=p->nextarc;
printf("\n\n");
}
}
}
int main()
{
ALGraph G;
createALGraph(&G);
printALGraph(G);
return 0;
}
图的邻接表存储
最新推荐文章于 2024-10-30 09:10:41 发布