//---------图的邻接表存储表示------- #include<stdio.h> #include<stdlib.h> #define MAX_VERTEXT_NUM 20 typedef int InfoType; typedef char VertextType; typedef struct ArcNode { int adjvex; struct ArcNode *nextArc; InfoType *info; }ArcNode; typedef struct VNode { VertextType data; ArcNode *firstArc; }VNode, AdjList[MAX_VERTEXT_NUM]; typedef struct { AdjList verTices; int vexNum; int arcNum; int kind; }ALGraph; void CreateGraph(ALGraph *G); void DisplayGraph(ALGraph *G); int main() { ALGraph *Graph = (ALGraph *)malloc(sizeof(ALGraph)); CreateGraph(Graph); DisplayGraph(Graph); system("pause"); } void CreateGraph(ALGraph *G) { int i,j,k; ArcNode *arcNode; printf_s("请输入顶点数和边数:"); scanf_s("%d,%d",&G->vexNum, &G->arcNum); //建立顶点表 printf_s("建立顶点表\n"); for (i = 0; i < G->vexNum; i++) { printf_s("请输入第%d个顶点:", i); fflush(stdin);//刷新缓冲区 G->verTices[i].data = getchar(); G->verTices[i].firstArc = NULL; } //建立边表 printf_s("建立边表\n"); for (k = 0; k < G->arcNum; k++) { printf_s("请输入(vi-vj)的顶点对序号"); scanf_s("%d,%d", &i, &j); arcNode = (ArcNode *)malloc(sizeof(ArcNode)); arcNode->adjvex = j; arcNode->nextArc = G->verTices[i].firstArc;//插入表头 G->verTices[i].firstArc = arcNode; arcNode = (ArcNode *)malloc(sizeof(ArcNode)); arcNode->adjvex = i; arcNode->nextArc = G->verTices[j].firstArc;//插入表头 G->verTices[j].firstArc = arcNode; } } void DisplayGraph(ALGraph *G) { int i; for (i = 0; i < G->vexNum; i++) { printf_s("%d->", i); while (G->verTices[i].firstArc != NULL) { printf_s("%d->", G->verTices[i].firstArc->adjvex); G->verTices[i].firstArc = G->verTices[i].firstArc->nextArc; } printf_s("\n"); } }
请输入顶点数和边数:6,7 建立顶点表 请输入第0个顶点:0 请输入第1个顶点:1 请输入第2个顶点:2 请输入第3个顶点:3 请输入第4个顶点:4 请输入第5个顶点:5 建立边表 请输入(vi-vj)的顶点对序号0,1 请输入(vi-vj)的顶点对序号0,4 请输入(vi-vj)的顶点对序号1,4 请输入(vi-vj)的顶点对序号1,5 请输入(vi-vj)的顶点对序号2,3 请输入(vi-vj)的顶点对序号2,5 请输入(vi-vj)的顶点对序号3,5 0->4->1-> 1->5->4->0-> 2->5->3-> 3->5->2-> 4->1->0-> 5->3->2->1-> 请按任意键继续. . .