【資料結構】鄰接表的儲存結構 建立圖的鄰接表演算法
阿新 • • 發佈:2018-11-24
一個圖的鄰接矩陣的表示是唯一的,但其鄰接表表示不唯一,這是因為在鄰接表結構中,各便表結點的連結次序取決於建立鄰接表時的演算法以及輸入的次序。
一般而言鄰接矩陣適合儲存稠密圖,鄰接表適合儲存稀疏圖。
直接輸入:
#include <stdio.h> #include <stdlib.h> #define M 20 /*鄰接表的儲存結構*/ typedef struct node /*表結點 或者 邊表結點*/ { int adjvex; struct node *next; }edgenode; typedef struct vnode /*頭結點*/ { char vertex; edgenode *firsteage; }vertexnode; typedef struct /*鄰接表型別*/ { vertexnode adjlist[M]; int n,e; }linkedgraph; //建立圖的鄰接表(檔案 或者 直接輸入) void creat(linkedgraph *g,int c) { int i,j,k; edgenode *s; printf("請輸入頂點數和邊數:\n"); scanf("%d%d",&g->n,&g->e); getchar(); printf("請依次輸入各個頂點的值:\n"); for(i=0;i<g->n;i++) { scanf("%c",&g->adjlist[i].vertex); g->adjlist[i].firsteage=NULL; } printf("請輸入有關係的邊:\n"); for(k=0;k<g->e;k++) { scanf("%d%d",&i,&j); s=(edgenode*)malloc(sizeof(edgenode)); s->adjvex=j; s->next=g->adjlist[i].firsteage; g->adjlist[i].firsteage=s; if(c==0)//無向圖 { s=(edgenode*)malloc(sizeof(edgenode)); s->adjvex=i; s->next=g->adjlist[j].firsteage; g->adjlist[j].firsteage=s; } } } void print(linkedgraph *g) { printf("\n\n輸出:\n"); edgenode *p; int i; printf("一共有%d個結點,%d條邊\n",g->n,g->e); for(i=0;i<g->n;i++) { p=g->adjlist[i].firsteage; printf("V%d -> ",i); while(p) { printf("%d",p->adjvex); if(p->next) printf(" -> "); p=p->next; } printf("\n"); } } int main () { linkedgraph g; creat(&g,1); print(&g); return 0; }
使用檔案操作:
void creat (linkedgraph *g,int c) { int i,j,k; edgenode *s; FILE *f; f=fopen("test.txt","r"); if(f) { fscanf(f,"%d%d",&g->n,&g->e); for(i=0;i<g->n;i++) { fscanf(f,"%1s",&g->adjlist[i].vertex); g->adjlist[i].firsteage=NULL; } for(k=0;k<g->e;k++) { fscanf(f,"%d%d",&i,&j); s=(edgenode*)malloc(sizeof(edgenode)); s->adjvex=j; s->next=g->adjlist[i].firsteage; g->adjlist[i].firsteage=s; if(c==0) { s=(edgenode*)malloc(sizeof(edgenode)); s->adjvex=i; s->next=g->adjlist[j].firsteage; g->adjlist[j].firsteage=s; } } fclose(f); } else { g->n=0; } }