Example 1 — Build and print adjacency lists
Each undirected edge is added in both directions.
#include <stdio.h>
#include <stdlib.h>
#define V 4
struct Edge { int to; struct Edge *next; };
static void add_edge(struct Edge *adj[], int u, int v) {
struct Edge *e = malloc(sizeof *e);
if (!e) exit(1);
e->to = v;
e->next = adj[u];
adj[u] = e;
}
int main(void) {
struct Edge *adj[V] = {0};
int edges[][2] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
for (int i = 0; i < 4; i++) {
add_edge(adj, edges[i][0], edges[i][1]);
add_edge(adj, edges[i][1], edges[i][0]);
}
for (int u = 0; u < V; u++) {
printf("%d:", u);
for (struct Edge *e = adj[u]; e; e = e->next) printf(" %d", e->to);
printf("\n");
}
for (int u = 0; u < V; u++) {
struct Edge *e = adj[u];
while (e) { struct Edge *n = e->next; free(e); e = n; }
}
return 0;
} How It Works
- Head insertion lists the newest neighbor first.
- Vertex 2 gets neighbors 0, 1, then 3, which print as 3, 1, 0.
- Every list is freed at the end.
