Represent a graph using an adjacency list.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int vertexNumber;
struct node * next;
} node;
typedef struct {
int V;
int E;
node** Adj; //array of linked list
} Graph;
Graph* adjacencyList() {
int i, x, y;
node * temp, *temp2;
Graph* G=(Graph*) malloc(sizeof(Graph));
printf("Enter the number of Vertices: ");
scanf("%d", &G->V);
printf("Enter the number of Edges: ");
scanf("%d", &G->E);
G->Adj = (node **)malloc(G->V * sizeof(node));
for (i = 0; i < G->V; i++) {
G->Adj[i] = (node *)malloc(G->V * sizeof(node));
G->Adj[i]->vertexNumber = i;
G->Adj[i]->next = NULL;
}
for (i = 0; i < G->E; i++) {
printf("Enter the edge: ");
scanf("%d %d", &x,&y);
temp = (node*)malloc(sizeof(node));
temp->vertexNumber = y;
temp->next = NULL;
temp2 = G->Adj[x];
while (temp2->next != NULL)
temp2 = temp2->next;
temp2->next = temp;
}
return G;
}
void test() {
int u, v;
Graph *G = adjacencyList();
node * temp;
for (u = 0; u < G->V; u++)
{
do {
printf("%4d\t", G->Adj[u]->vertexNumber);
G->Adj[u] = G->Adj[u]->next;
} while ( G->Adj[u]!=NULL);
printf("\n");
}
}
int main()
{
test();
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of a deque using a doubly-linked list