鄰接表表示圖
阿新 • • 發佈:2018-03-11
還要 day size tro OS 信息 def sizeof 指針
對於鄰接表,G[N]為指針數組,對應矩陣每行一個鏈表,只存非0元素
- 指針數組裏的每一個指針都是一個單鏈表的頭指針,單鏈表裏每個節點裏存儲的是圖中每條邊的信息。
- 鄰接表包括一個頂點表和一個邊表。頂點表包括頂點和指向下一個鄰接點的指針,
邊表存儲的是鄰接點點序號和指向下一個的指針剛開始的時候把頂點表初始化,指針指向null。
然後邊表插入進來,是插入到前一個,也就是直接插入到firstedge指向的下一個,而後面的後移
0、結構初始化
//對鄰接點(弧節點/邊表節點)
struct ENode {
int position; /* 鄰接點下標 */
WeightType weight; /* 邊權重 */
EdgeNode* next; /* next指針 */
};
//對於頭結點(頂點表節點)
typedeft struct VNode {
struct ENode* firstEdge; /* 第一個表結點的地址,指向第一條依附該頂點的弧的指針 */
ElementType data; /* 存頂點數據 */
}AdjList[maxVertexNum];
//對整個圖
struct GraphNode {
int Nv; /* 頂點數 */
int Ne; /* 邊數 */
AdjList G; /* 鄰接表(數組),AdjList為鄰接表類型 */
};
//邊結構
struct EdgeNode {
int v1,v2; /* 有向邊 */
WeightType weight; /* 權重 */
};
1、圖的初始化
//初始化一個有VertexNum個頂點但沒有邊的圖
struct GraphNode* createGraph(int vertexNum) {
struct GraphNode* Graph;
Graph=(struct GraphNod*)malloc(sizeof(struct GraphNode));
Graph->Nv=vertexNum;
Graph->Ne=0 ;
/* 註意頂點編號從0開始 */
for (int i=0;i<Graph->Nv;i++) {
Graph->G[i].firstEdge=NULL;
}
return Graph;
}
2、向圖中插入邊
圖解如下:
void insertEdge(struct GraphNode* Graph,struct EdgeNode* E) {
struct ENode* temp;
/* 將邊<v1,v2>插入,此時已經有v1在表頭了 */
/* 為v2創建新的鄰接點 */
/* 將v2插入v1的表頭 */
temp=(struct ENode*)malloc(sizeof(struct ENode));
temp->position=E->v2;
temp->weight=E->weight;
temp->next=Graph->G[v1].firstEdge;
Graph->G[v1].firstEdge=temp;
/* 如果是無向圖,還要插入邊<v2,v1> */
/* 為v1創建新的鄰接點 */
/* 將v1插入v2的表頭 */
temp=(struct ENode*)malloc(sizeof(struct ENode));
temp->position=E->v1;
temp->weight=E->weight;
temp->next=Graph->G[v2].firstEdge;
Graph->G[v2].firstEdge=temp;
}
3、完整建立一個Graph
//與前面鄰接矩陣基本相同,只有小小的差別
struct GraphNode* buildGraph() {
struct GraphNode* Graph;
struct EdgeNode* E;
int Nv;
scanf("%d",&Nv);
Graph=createGraph(Nv);
scanf("%d",&Ne);
if (Graph->Ne!=0) {
E=(struct EdgeNode*)malloc(sizeof(struct EdgeNode));
for (int i=0;i<Ne;i++) {
scanf("%d %d %d",E->v1,E->v2,E->weight);
insertEdge(Graph,E);
}
}
/* 如果頂點有數據的話存入數據 */
for (int j=0;j<Nv;j++) {
scanf("%c",&(Graph->G[i].Data));
/* 僅僅是這裏與前面不一樣 */
}
return Graph;
}
鄰接表表示圖