The data structure used is
One is the vertex table, including the vertex and pointer pointing to the next adjacent point.
One is an edge table. The data structure is different from the vertex. It stores the vertex sequence number and points to the next pointer.
Initialize the vertex table at the beginning and point the pointer to null. Insert the edge table to the previous one, that is, insert it directly to the next one pointed to by firstedge, and move the back
# Define maxvertexnum 100 typedef char vertextype; typedef struct node // edge table node {int adjvex; node * Next;} edgenode; typestrudef CT // vertex table node {vertextype vertex; edgenode * firstedge;} vertexnode; typedef vertexnode adjlist [maxvertexnum]; typedef struct {adjlist; int N, E;} algraph;
The following is an undirected graph adjacent table, which is simpler.
# Include <stdio. h> # include <stdlib. h> # define maxvertexnum 100 typedef char vertextype; typedef struct node // edge table node {int adjvex; node * Next;} edgenode; typedef struct // vertex table node {vertextype vertex; edgenode * firstedge;} vertexnode; typedef vertexnode adjlist [maxvertexnum]; typedef struct {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 ("Number of vertices and edges read"); scanf ("% d, % d", & G-> N, & G-> E ); for (I = 0; I <G-> N; I ++) {fflush (stdin); printf ("create vertex table"); G-> adjlist [I]. vertex = getchar (); G-> adjlist [I]. firstedge = NULL;} printf ("create edge table \ n"); For (k = 0; k <G-> E; k ++) {printf ("vertex pair number of read (Vi-VJ)"); scanf ("% d, % d", & I, & J); s = (edgenode *) malloc (sizeof (edgenode); s-> adjvex = J; s-> next = G-> adjlist [I]. firstedge; // Insert the header G-> adjlist [I]. firstedge = s; S = (edgenode *) malloc (sizeof (edgenode); s-> adjvex = I; s-> next = G-> adjlist [J]. firstedge; G-> adjlist [J]. firstedge = s ;}}
Result
Try programming on your own!
Next, we will traverse the graph in depth first and breadth first.