Figure shows
The previous blog has already said two representations of the graph, one is the adjacency list, and the other is the adjacency matrix method.
The front is suitable for sparse graphs, and the latter is naturally suitable for dense graphs.
Graph creating adjacency matrices
Adjacency matrix is actually a two-dimensional matrix, in front of the diagram is already simple to say, directly set up a direct int G[NumVertex][NumVertex]
input on the good.
The following is an emphasis on the Adjacency list method.
Adjacency linked List
The presentation method has already been said, the Portal: Diagram representation.
Here's a look at the code:
structnode{intValintLength Node* Next; Node (): Val (0), Length (0), Next (NULL) {}};typedefnode* Graph; Graph Createg (graph G) {intNumscanf("%d", &num);//Input The number of the vertexG = (Graph)malloc(sizeof(structNode) * (num+1));//malloc Memory for graphg[0].length = num;//save The graph vertex numberdegree = (int*)malloc((num+1) *sizeof(int));memset(Degree,0, num*sizeof(int)); for(inti =1; I <= num; i++) {g[i].val = i; G[i].next = NULL;intOutdegree =0;scanf("%d", &outdegree); for(intj =0; J < Outdegree; J + +) {node* temp = (node*)malloc(sizeof(structNode));scanf("%d%d",& (Temp->val), & (Temp->length)); Temp->next = G[i].next; G[i].next = temp; Degree[temp->val] + =1; } }returnG;}
This is the code that was created.
Figure Printing adjacency List
Print here only the adjacency list method, because the matrix is also very simple. for
It's the two-story loop that solves it.
Here's the code for the adjacency list:
void Printg (Graph G) {// int length= sizeof (G)/sizeof (struct Node);int length= g[0].length; Node * TEMP; for(inti =1; I <=length; i++) {temp = &G[i];printf("Node: %d ", Temp->val); while(temp->Next) {printf("- %d(%d)",temp->Next->val, temp->Next-length); temp = temp->Next; }printf("\ n"); }}
The code is above, and I don't have the number of vertices in g[0].length that have saved the entire list.
Algorithm learning-creation and printing of graphs