用鄰接表方式建立圖
阿新 • • 發佈:2019-02-14
//用鄰接表表示圖 #include <stdio.h> #include <stdlib.h> #define DataType char #define MaxVertexNum 20 #define Vertex int #define WeightType int typedef struct GNode *PtrToGNode; struct GNode { int Nv; //頂點數 int Ne; //邊數 AdjList G; //鄰接表 }; struct ENode{ Vertex v1, v2; int weight; }; typedef struct ENode* Edge; typedef PtrToGNode LGraph; //以鄰接表方式儲存的圖型別 typedef struct Vnode { PtrToAdjVNode FirstEdge; DataType Data; //存頂點的資料 }AdjList[MaxVertexNum]; typedef struct AdjVNode *PtrToAdjVNode; struct AdjVNode { Vertex AdjV; //鄰接點下標 WeightType Weight; //邊的權重 PtrToAdjVNode Next; }; //初始化一個有VertexNum個頂點但沒有邊的圖 LGraph CreateGraph(int VertexNum) { Vertex v; LGraph Graph; Graph = (LGraph)malloc(sizeof(struct GNode)); Graph->Nv = VertexNum; Graph->Ne = 0; for (v = 0; v < Graph->Nv; v++) Graph->G[v].FirstEdge = NULL; return Graph; } void InsertEdged(LGraph Graph, Edge E) { PtrToAdjVNode NewNode; NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode)); NewNode->AdjV = E->v2; NewNode->Weight = E->weight; //將v2插入v1的表頭 NewNode->Next = Graph->G[E->v1].FirstEdge; Graph->G[E->v1].FirstEdge = NewNode; //若是無向圖,還要插入邊<v2, v1> //為v1建立新的鄰接點 NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode)); NewNode->AdjV = E->v1; NewNode->Weight = E->weight; //將v1插入v2的表頭 NewNode->Next = Graph->G[E->v2].FirstEdge; Graph->G[E->v2].FirstEdge = NewNode; }