1. 程式人生 > >圖的鄰接表儲存c實現

圖的鄰接表儲存c實現

用到的資料結構是

一個是頂點表,包括頂點和指向下一個鄰接點的指標

一個是邊表, 資料結構跟頂點不同,儲存的是頂點的序號,和指向下一個的指標

剛開始的時候把頂點表初始化,指標指向null。然後邊表插入進來,是插入到前一個,也就是直接插入到firstedge指向的下一個,而後面的後移

[cpp] view plaincopyprint?
  1. #define  MaxVertexNum 100
  2. typedefchar VertexType;  
  3. typedefstruct node   //邊表節點
  4. {  
  5.    int adjvex;  
  6.    node* next;  
  7. }EdgeNode;  
  8. typedef
    struct//頂點表節點
  9. {  
  10.    VertexType vertex;  
  11.    EdgeNode* firstedge;  
  12. }VertexNode;  
  13. typedef VertexNode AdjList[MaxVertexNum];  
  14. typedefstruct
  15. {   
  16.     AdjList adjlist;  
  17.     int n,e;  
  18. }ALGraph;  


以下建立的是無向圖的鄰接表,有向圖的更簡單了

[cpp] view plaincopyprint?
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define  MaxVertexNum 100
  4. typedefchar VertexType;  
  5. typedefstruct node   //邊表節點
  6. {  
  7.    int adjvex;  
  8.    node* next;  
  9. }EdgeNode;  
  10. typedefstruct//頂點表節點
  11. {  
  12.    VertexType vertex;  
  13.    EdgeNode* firstedge;  
  14. }VertexNode;  
  15. typedef VertexNode AdjList[MaxVertexNum];  
  16. typedefstruct
  17. {   
  18.     AdjList adjlist;  
  19.     int n,e;  
  20. }ALGraph;  
  21. void create(ALGraph*);  
  22. void main()  
  23. {  
  24.    ALGraph* G= (ALGraph*)malloc(sizeof(ALGraph));  
  25.    create(G);  
  26.    for (int i=0;i< G->n;i++)  
  27.    {  
  28.        printf("%d->",i);  
  29.        while(G->adjlist[i].firstedge!=NULL)  
  30.        {  
  31.             printf("%d->",G->adjlist[i].firstedge->adjvex);  
  32.             G->adjlist[i].firstedge=G->adjlist[i].firstedge->next;  
  33.        }  
  34.        printf("\n");  
  35.    }  
  36. }  
  37. void create(ALGraph* G)  
  38. {  
  39.     int i,j,k,w,v;  
  40.     EdgeNode *s;  
  41.     printf("讀入頂點數和邊數");  
  42.     scanf("%d,%d",&G->n,&G->e);  
  43.    for (i=0;i<G->n;i++)  
  44.    {  
  45.        fflush(stdin);  
  46.        printf("建立頂點表");  
  47.        G->adjlist[i].vertex=getchar();  
  48.        G->adjlist[i].firstedge=NULL;  
  49.    }  
  50.    printf("建立邊表\n");  
  51.    for (k=0;k<G->e;k++)  
  52.    {  
  53.        printf("讀入(vi-vj)的頂點對序號");  
  54.        scanf("%d,%d",&i,&j);  
  55.        s=(EdgeNode*)malloc(sizeof(EdgeNode));  
  56.        s->adjvex=j;  
  57.        s->next=G->adjlist[i].firstedge;  //插入表頭
  58.        G->adjlist[i].firstedge=s;  
  59.        s=(EdgeNode*)malloc(sizeof(EdgeNode));  
  60.        s->adjvex=i;  
  61.        s->next=G->adjlist[j].firstedge;  
  62.        G->adjlist[j].firstedge=s;  
  63.    }  
  64. }  


結果

自己也程式設計試試吧!

接下來圖的遍歷,深度優先遍歷和廣度優先遍歷。