圖(一)之鄰接表Adjacency List
阿新 • • 發佈:2019-01-27
開始攻克圖的演算法,先從最簡單的儲存開始實現,本文關於鄰接表的實現。
鄰接表是圖的儲存中最簡單也是最基本的儲存結構,基於連結串列的思想實現的。在鄰接表中,對於中的每個頂點建立一個單鏈表,第i個單鏈表中的節點表示依附於頂點的vi的邊。每個節點由3個域組成其中鄰接點域(adjvex)指示與頂點vi鄰接的點在圖中的位置,鏈域(nextarc)指示下一條邊或弧的節點;資料域(info)儲存和邊或弧相關的資訊,如權值等,每個連結串列上附設一個表頭節點。在表頭節點中除了設有鏈域(firstarc)指向連結串列中的第一個節點之外,還設有儲存頂點vi的名或其他有關資訊的資料域(data)。
兩種表結構如圖:
我以下面的圖結構為例進行操作:
下面把程式碼貢獻出來:
Adj_List.h
#ifndef __ADJ_LIST_H__ #define __ADJ_LIST_H__ #define MAX_VERTEX_NUM 20 typedef struct ArcNode { char adjvex; struct ArcNode *nextarc; int *info; }ArcNode; typedef struct VNode { char data; ArcNode *firstarc; }VNode,AdjList[MAX_VERTEX_NUM]; typedef struct ALGraph { AdjList vertices; int vexnum,arcnum; int kind; }ALGraph; #endif /* __ADJ_LIST_H__*/
graph_storage.c
也可以從我的GitHub clone/* ************************************************ *Name : graph_storage.c * *Date : 2015-05-27 * *Author : sniper * *Aim : It will storage the graph using the adj-* * acency list,and travel the pragh. * ************************************************ */ #include <stdio.h> #include <stdlib.h> #include "Adj_list.h" int create(ALGraph *G) { int i,j; int node_pair1,node_pair2; ArcNode *arc; node_pair1=0; node_pair2=0; i=0; j=0; printf("please input the number of node and edge: "); scanf("%d %d",&G->vexnum,&G->arcnum); for(i=0;i<G->vexnum;i++) { G->vertices[i].data = 'A'+i; G->vertices[i].firstarc = NULL; } printf("finish the Node!\n"); for(j=0;j<G->arcnum;j++) { printf("please input the node pair: "); scanf("%d %d",&node_pair1,&node_pair2); node_pair1-=1; node_pair2-=1; /* *Node pair get match with each other *and storage into the adjacency list. */ arc = (ArcNode *)malloc(sizeof(ArcNode)); arc->adjvex = node_pair2+'A'; arc->nextarc=G->vertices[node_pair1].firstarc; G->vertices[node_pair1].firstarc=arc; arc = (ArcNode *)malloc(sizeof(ArcNode)); arc->adjvex = node_pair1+'A'; arc->nextarc=G->vertices[node_pair2].firstarc; G->vertices[node_pair2].firstarc=arc; } printf("finish the Adjacency List\n"); return 0; } int main() { ALGraph *G; int i; i=0; G = (ALGraph *)malloc(sizeof(ALGraph)); create(G); /* *print the adjacency list */ for(i=0;i<G->vexnum;i++) { printf("%c -> ",'A'+i); while(G->vertices[i].firstarc!=NULL) { printf("%c -> ",G->vertices[i].firstarc->adjvex); G->vertices[i].firstarc=G->vertices[i].firstarc->nextarc; } printf("\n"); } return 0; }
測試用例:
5 6
1 2
1 4
2 3
2 5
3 4
3 5
好了下次該解決下面的問題了!