#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef char Vertex_Type[5];
typedef enum
{
DG, DN, UDG, UDN
}Graph_Kind;
typedef struct Arc_Node
{
int adjvex;//表示邻接顶点在向量表中的位置
struct Arc_Node *next_arc;
int weight;//表示权
}Arc_Node;
typedef struct Vertex_Node
{
Vertex_Type data;
Arc_Node *first_arc;
}Vertex_Node;
typedef struct
{
Vertex_Node vertexs_vectors[MAX_VERTEX_NUM];
int vertex_num;
int arc_num;
Graph_Kind kind;
}ALGraph;
//初始化图中的有关信息
void Init_ALGraph( ALGraph &G )
{
printf("输入图的类型(DG:0 DN:1 UDG:2 UDN:3): ");
scanf("%d", &G.kind );
printf("输入图的顶点数:");
scanf("%d", &G.vertex_num );
printf("输入图的边数:");
scanf("%d", &G.arc_num );
int i;
printf("输入定点向量:");
for( i=0; i<G.vertex_num; ++i )
{
scanf("%s", G.vertexs_vectors[i].data);
G.vertexs_vectors[i].first_arc = NULL;
}
}
//获取定点在定点向量中的位置 如果出错就终止运行
int Get_Vertex_Location( ALGraph G, Vertex_Type V )
{
int i;
for( i=0; i<G.vertex_num; ++i )
if( strcmp( V, G.vertexs_vectors[i].data ) == 0 )
return i;
exit(0);
}
void Greate_ALGraph( ALGraph &G )
{
Init_ALGraph( G );
Vertex_Type vertex_1, vertex_2;
int i, v1_site, v2_site;
printf("输入图的弧(形如 v1 - v2):\n");
for( i=0; i<G.arc_num; ++i )
{
scanf("%s %*s %s", vertex_1, vertex_2);
v1_site = Get_Vertex_Location( G, vertex_1 );
v2_site = Get_Vertex_Location( G, vertex_2 );
Arc_Node *p1, *p2;
p1 = (Arc_Node *) malloc (sizeof(Arc_Node));
p1->adjvex = v2_site;
p1->weight = 0;//初始化权值为零
p1->next_arc = G.vertexs_vectors[v1_site].first_arc;
G.vertexs_vectors[v1_site].first_arc = p1;
switch( G.kind )
{
case DG:
break;
case DN:
printf("输入权值:");
scanf("%d", &p1->weight );
break;
case UDG:
p2 = (Arc_Node *) malloc (sizeof(Arc_Node));
p2->adjvex = v1_site;
p2->weight = 0;//初始化权值为零
p2->next_arc = G.vertexs_vectors[v2_site].first_arc;
G.vertexs_vectors[v2_site].first_arc = p2;//头插入
break;
case UDN:
printf("输入权值:");
scanf("%d", &p1->weight );
p2 = (Arc_Node *) malloc (sizeof(Arc_Node));
p2->adjvex = v1_site;
p2->weight = p1->weight;//初始化权值为零
p2->next_arc = G.vertexs_vectors[v2_site].first_arc;
G.vertexs_vectors[v2_site].first_arc = p2;//头插入
break;
default:
exit(0);
}
}
}
void Print_ALGraph( ALGraph G )
{
int i;
for( i=0; i<G.vertex_num; ++i )
{
Arc_Node *p = G.vertexs_vectors[i].first_arc;
while( p )
{
switch( G.kind )
{
case UDG:
printf("( %s --", G.vertexs_vectors[i].data);
printf(" %s )", G.vertexs_vectors[p->adjvex].data);break;
case UDN:
printf("( %s --", G.vertexs_vectors[i].data);
printf(" %s , %d )", G.vertexs_vectors[p->adjvex].data, p->weight);break;
case DG:
printf("< %s ->", G.vertexs_vectors[i].data);
printf(" %s >", G.vertexs_vectors[p->adjvex].data);break;
case DN:
printf("< %s ->", G.vertexs_vectors[i].data);
printf(" %s , %d >", G.vertexs_vectors[p->adjvex].data, p->weight);break;
default:
exit(0);
}
p = p->next_arc;
printf("\n");
}
}
}
int main()
{
ALGraph G;
Greate_ALGraph( G );
Print_ALGraph( G );
return 0;
}