#include <stdio.h>
#include <stdlib.h>
// Node for adjacency list
typedef struct Node {
int dest;
struct Node* next;
} Node;
// Graph structure
typedef struct Graph {
int V;
Node** array;
} Graph;
// Create new adjacency list node
Node* newNode(int dest) {
Node* node = (Node*)malloc(sizeof(Node));
node->dest = dest;
node->next = NULL;
return node;
}
// Create graph with V vertices
Graph* createGraph(int V) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->array = (Node**)malloc(V * sizeof(Node*));
for (int i = 0; i < V; i++)
graph->array[i] = NULL;
return graph;
}
// Add edge to undirected graph
void addEdge(Graph* graph, int src, int dest) {
// Add node to src list
Node* node = newNode(dest);
node->next = graph->array[src];
graph->array[src] = node;
// Add node to dest list
node = newNode(src);
node->next = graph->array[dest];
graph->array[dest] = node;
}
// Print adjacency list
void printGraph(Graph* graph) {
for (int v = 0; v < graph->V; v++) {
Node* pCrawl = graph->array[v];
printf("%d: ", v);
while (pCrawl) {
printf("%d -> ", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("null\n");
}
}
int main() {
int V = 4;
Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
printGraph(graph);
return 0;
}
node->next = graph->array[src];
graph->array[src] = node;
Insert new neighbor at head of src adjacency list
node->next = graph->array[dest];
graph->array[dest] = node;
Insert new neighbor at head of dest adjacency list for undirected edge
while (pCrawl) {
printf("%d -> ", pCrawl->dest);
pCrawl = pCrawl->next;
}
Traverse adjacency list to print all neighbors
0: 2 -> 1 -> null
1: 3 -> 0 -> null
2: 0 -> null
3: 1 -> null