有向圖的建立與遍歷(鄰接連結串列)
阿新 • • 發佈:2018-12-08
下面介紹一下,有向圖的建立與遍歷(使用鄰接連結串列法)
思路:在頂點結構體裡面,將第一條邊用指向邊的結構體的指標firstedge儲存
即struct EdgeNode * next;
1.再輸入,邊的個數,頂點的個數。
2.輸入所有節點的字母
3.最後再輸入所有的邊的字母(例如,輸入AB就代表,A的出度指向B)即可
相應的註釋都寫在程式碼裡
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<stdbool.h> typedef struct EdgeNode { int adjvex; //邊的中點 int weight; //邊的權值(若不需要可以無視) struct EdgeNode * next; //指向下一個節點的指標 }EdgeNode; typedef struct VertexNode { //頂點結構體 char data; //資料 EdgeNode * firstedge; //第一條邊 int inNum; //入度 int outnum; //出度 }VertexNode, AdjList[200]; typedef struct { AdjList adjList; int numVertexes, numEdges; //邊數,頂點數 bool visted[50]; //標記是否訪問過該節點,在遍歷時會使用到 }GraphAdjList; //有向圖的建立 void CreateALGraph2(GraphAdjList * G) { int i, j, k; char a, b; //用來輸入兩個邊的字母 int ii, jj; //標記字母對應的下標 EdgeNode * e; printf("Please input the num of vert and edge:"); scanf("%d%d", &G->numVertexes, &G->numEdges); getchar(); printf("請輸入頂點的各個字母:"); char verts[200]; //儲存所有頂點的字母 gets_s(verts, 200); //初始化節點 for (i = 0; i < G->numVertexes; i++) { G->adjList[i].data = verts[i]; G->adjList[i].firstedge = (EdgeNode*)malloc(sizeof(EdgeNode)); G->adjList[i].firstedge->next = NULL; //注意!這裡不使用頭節點 G->adjList[i].inNum = G->adjList[i].outnum = 0; //將入度和出度置為0 } //建立邊表 for (k = 0; k < G->numEdges; k++) { printf("輸入邊的起點和終點字母:"); scanf("%c%c", &a, &b); getchar(); //尋找起點字母的位置 for (i = 0; i < G->numVertexes; i++) { if (G->adjList[i].data == a) { ii = i; G->adjList[i].outnum++;//出度 break; } } //尋找終點字母的位置 for (i = 0; i < G->numVertexes; i++) { if (G->adjList[i].data == b) { jj = i; G->adjList[i].inNum++;//入度 break; } } //使用頭插法建立,將firstedge當作頭結點使用 e = (EdgeNode *)malloc(sizeof(EdgeNode)); e->next = G->adjList[i].firstedge->next; e->adjvex = jj; //將邊的下標儲存 G->adjList[i].firstedge->next = e; } printf("建立完成\n"); } int main(int argc, const char * argv[]) { GraphAdjList G; CreateALGraph2(&G); for (int i = 0; i < G.numVertexes; i++) { printf("%c %d %d %d\n", G.adjList[i].data, G.adjList[i].outnum, G.adjList[i].inNum, G.adjList[i].inNum + G.adjList[i].outnum); } putchar('\n'); return 0; }
結果如下圖所示