圖的鄰接表格儲存體 c實現

來源:互聯網
上載者:User

 

用到的資料結構是

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

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

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

 

#define  MaxVertexNum 100typedef char VertexType;typedef struct node   //邊表節點{   int adjvex;   node* next;}EdgeNode;typedef struct     //頂點表節點{   VertexType vertex;   EdgeNode* firstedge;}VertexNode;typedef VertexNode AdjList[MaxVertexNum];typedef struct { AdjList adjlist;int n,e;}ALGraph;

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

#include <stdio.h>#include <stdlib.h>#define  MaxVertexNum 100typedef char VertexType;typedef struct node   //邊表節點{   int adjvex;   node* next;}EdgeNode;typedef struct     //頂點表節點{   VertexType vertex;   EdgeNode* firstedge;}VertexNode;typedef VertexNode AdjList[MaxVertexNum];typedef struct { AdjList adjlist;int n,e;}ALGraph;void create(ALGraph*);void main(){   ALGraph* G= (ALGraph*)malloc(sizeof(ALGraph));   create(G);   for (int i=0;i< G->n;i++)   {   printf("%d->",i);   while(G->adjlist[i].firstedge!=NULL)   {printf("%d->",G->adjlist[i].firstedge->adjvex);G->adjlist[i].firstedge=G->adjlist[i].firstedge->next;   }   printf("\n");   }}void create(ALGraph* G){    int i,j,k,w,v;    EdgeNode *s;printf("讀入頂點數和邊數");    scanf("%d,%d",&G->n,&G->e);     for (i=0;i<G->n;i++)   {   fflush(stdin);   printf("建立頂點表");   G->adjlist[i].vertex=getchar();   G->adjlist[i].firstedge=NULL;   }   printf("建立邊表\n");   for (k=0;k<G->e;k++)   {   printf("讀入(vi-vj)的頂點對序號");   scanf("%d,%d",&i,&j);   s=(EdgeNode*)malloc(sizeof(EdgeNode));   s->adjvex=j;   s->next=G->adjlist[i].firstedge;  //插入表頭   G->adjlist[i].firstedge=s;   s=(EdgeNode*)malloc(sizeof(EdgeNode));   s->adjvex=i;   s->next=G->adjlist[j].firstedge;   G->adjlist[j].firstedge=s;   }}

結果

自己也編程試試吧!

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.