1, define the structure of the diagram:
1 #defineNum_max 62typedefstructarcnode{3 intAdjvex;4 structArcnode *Nextarc;5}arcnode;//define an ARC node structure body6typedefstructvertexnode{7 intdata;8Arcnode *Firstarc;9}vertexnode;//defining the vertex structure bodyTentypedefstruct { OneVertexnode *Adjlist[num_max]; A intVertexnum,edgenum; - intGraphtype; -}linkgraph;//definition Diagram
2. Define the function that creates the adjacency table of the graph
1 voidCreatelink (Linkgraph *LG) {2 intStart,end;3Arcnode *s;4 for(intI=1; i<=lg->vertexnum;i++){5(Lg->adjlist[i]) = (Vertexnode *)malloc(sizeof(Vertexnode));//If there is no memory space, then lg->adjlist[i] is empty. This is the difference between a pointer variable and an entity variable6(Lg->adjlist[i])->data=i;7(Lg->adjlist[i])->firstarc=NULL;8 }9 for(intI=1; i<=lg->edgenum;i++){Tenprintf"Please input the vertexes of the %dth edge\n", i); Onescanf"%d%d",&start,&end); As= (Arcnode *)malloc(sizeof(Arcnode)); -s->adjvex=end; -S->nextarc=lg->adjlist[start]->Firstarc; theLg->adjlist[start]->firstarc=s; - } -}
3. Define Output adjacency table function
1 voidOutPut (Linkgraph *LG) {2Arcnode *s;3 for(intI=1; i<=lg->vertexnum;i++){4printf"The vertex%d:", i);5S=lg->adjlist[i]->Firstarc;6 while(s) {7printf"- %d",s->Adjvex);8S=s->Nextarc;9 }Tenprintf"\ n"); One } A -}
4. Main function:
1 intMain () {2Linkgraph *LG;3lg= (linkgraph*)malloc(sizeof(Linkgraph));4printf"Please input the vertexnum and Edgenum:");5scanf"%d%d",&lg->vertexnum,&lg->edgenum);6 Createlink (LG);7printf"Output the linkgraph:\n");8 OutPut (LG);9 Free(LG);Ten getch (); One return 0; A}
View Code
Data structure----diagram (adjacency table usage)