圖的鄰接表表示法的實現
阿新 • • 發佈:2019-02-14
#include <stdio.h> #include <stdlib.h> #define MaxVertexNum 50 typedef struct node *EdgeNode; typedef struct vnode *VertexNode; typedef struct graph *ALGraph; struct node { //邊表節點 int adjvex; //鄰接點域 EdgeNode next; //鏈域 }; struct vnode { //頂點表節點 int vertex; //頂點域 EdgeNode firstedge; //邊表頭指標 }; struct graph { struct vnode *adjlist; int n; //圖中當前頂點數 int e; //圖中當前邊數 }; void CreatALGraph(ALGraph G) { int i, j, k; int a; EdgeNode s; //定義邊表節點 printf("請輸入頂點數和邊數:\n"); scanf("%d %d", &i, &j); G->n = i; G->e = j; printf("請輸入頂點編號:\n"); for (i = 1; i <= G->n; i++) //建立頂點表 { scanf("%d", &a); G->adjlist[i].vertex = a; //讀入頂點資訊 G->adjlist[i].firstedge = NULL; //邊表頭指標置為空 } printf("請輸入由兩個定點構成的邊,示例:0 1\n"); for (k = 0; k < G->e; k++) { scanf("%d %d", &i, &j); //讀入邊(Vi, Vj)的頂點對應的序號 s = malloc(sizeof(struct node)); //生成邊表節點 s->adjvex = j; s->next = G->adjlist[i].firstedge; G->adjlist[i].firstedge = s; //將新節點*s插入頂點Vi的邊表頭部 /*若建立為無向圖,則新增下面的程式碼*/ /* s = malloc(sizeof(struct node)); s->adjvex = i; s->next = G->adjlist[j].firstedge; G->adjlist[j].firstedge = s; */ } } int main() { int i, j; ALGraph G = malloc(sizeof(struct graph)); G->adjlist = (struct vnode *)malloc(sizeof(struct vnode) * MaxVertexNum); CreatALGraph(G); for (i = 1; i <= G->n; i++) { while (G->adjlist[i].firstedge) { printf("%d -> ", G->adjlist[i].vertex); printf("%d\n", G->adjlist[i].firstedge->adjvex); G->adjlist[i].firstedge = G->adjlist[i].firstedge->next; } } return 0; }