1 #include<stdio.h> 2 #include<stdlib.h> 3 #include "listGraph.cpp" 4 5 int main(void) { 6 listGraph G;//定義保存鄰接矩陣結構的圖 7 int i, j; 8 9 printf("請輸入生成圖的類型(0.無向圖, 1.有向圖):"); 10 scanf("%d", &G.graphType); 11 printf("請輸入圖的定點數量和邊的數量:"); 12 scanf("%d %d", &G.vertexNum, &G.edgeNum); 13 printf("輸入構成各邊的兩個頂點及權值:\n"); 14 createGraph(&G);//創建鄰接表保存的圖 15 printf("鄰接表數據如下:\n"); 16 outList(&G); 17 return 0; 18 } 19 20 void createGraph(listGraph* G) { 21 int i, weight; 22 int start, end; 23 edgeNode* s; 24 25 for (i = 1; i <= G->vertexNum; i++) G->adjList[i] = NULL;//將圖中的各頂點指針清空 26 for (i = 1; i <= G->edgeNum; i++) { 27 getchar(); 28 printf("第%d條邊:", i); 29 scanf("%d %d %d", &start, &end, &weight);//輸入邊的起點和終點及權值 30 s = (edgeNode*)malloc(sizeof(edgeNode));//申請保存一個頂點的內存 31 s->next = G->adjList[start];//插入到鄰接表中 32 s->vertex = end;//保存終點編號 33 s->weight = weight; 34 G->adjList[start] = s;//鄰接表對應頂點指向終點 35 //如果是無向圖,則需要再插入到終點的指針后 36 if (!G->graphType) { 37 s = (edgeNode*)malloc(sizeof(edgeNode)); 38 s->next = G->adjList[end]; 39 s->vertex = start; 40 s->weight = weight; 41 G->adjList[end] = s; 42 } 43 } 44 } 45 46 void outList(listGraph* G) { 47 int i; 48 edgeNode* s; 49 50 for (i = 1; i <= G->vertexNum; i++) { 51 printf("頂點%d", i); 52 s = G->adjList[i]; 53 while (s) { 54 printf("->%d(%d)", s->vertex, s->weight); 55 s = s->next; 56 } 57 printf("\n"); 58 } 59 }
#include "listGraph.cpp" 如下:
1 #define vertex_max 20 2 typedef struct Node { 3 int vertex;//定點序號 4 int weight;//權值 5 struct Node* next;//指向有邊的下一個頂點 6 }edgeNode; 7 8 typedef struct { 9 edgeNode* adjList[vertex_max];//指向每個頂點的指針 10 int vertexNum, edgeNum; 11 int graphType;//0表示無向圖,1有向圖 12 }listGraph; 13 14 void createGraph(listGraph* G);//生成圖的鄰接表 15 void outList(listGraph* G);//輸出鄰接表
