#include <stdio.h>
#include <stdlib.h>
// Node for adjacency list
typedef struct Node {
int vertex;
struct Node* next;
} Node;
// Graph with adjacency list
typedef struct Graph {
int numVertices;
Node** adjLists;
int** adjMatrix;
} Graph;
// Create node for list
Node* createNode(int v) {
Node* newNode = malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Create graph
Graph* createGraph(int vertices) {
Graph* graph = malloc(sizeof(Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(Node*));
graph->adjMatrix = malloc(vertices * sizeof(int*));
for (int i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->adjMatrix[i] = malloc(vertices * sizeof(int));
for (int j = 0; j < vertices; j++) {
graph->adjMatrix[i][j] = 0;
}
}
return graph;
}
// Add edge to adjacency list and matrix
void addEdge(Graph* graph, int src, int dest) {
// Add to list src->dest
Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add to list dest->src (undirected)
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
// Update matrix
graph->adjMatrix[src][dest] = 1;
graph->adjMatrix[dest][src] = 1;
}
// Print adjacency list
void printAdjList(Graph* graph) {
printf("Adjacency List:\n");
for (int i = 0; i < graph->numVertices; i++) {
printf("%d: ", i);
Node* temp = graph->adjLists[i];
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("null\n");
}
}
// Print adjacency matrix
void printAdjMatrix(Graph* graph) {
printf("Adjacency Matrix:\n ");
for (int i = 0; i < graph->numVertices; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 0; i < graph->numVertices; i++) {
printf("%d [", i);
for (int j = 0; j < graph->numVertices; j++) {
printf("%d", graph->adjMatrix[i][j]);
if (j < graph->numVertices - 1) printf(" ");
}
printf("]\n");
}
}
int main() {
Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
printAdjList(graph);
printAdjMatrix(graph);
// Add edge 2-3
addEdge(graph, 2, 3);
printf("\nAfter adding edge 2-3:\n");
printAdjList(graph);
printAdjMatrix(graph);
return 0;
}newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode;
insert new neighbor at head of adjacency list for src
newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode;
insert new neighbor at head of adjacency list for dest (undirected)
graph->adjMatrix[src][dest] = 1; graph->adjMatrix[dest][src] = 1;
mark edge in adjacency matrix for both directions
Adjacency List:
0: 2 -> 1 -> null
1: 3 -> 0 -> null
2: 0 -> null
3: 1 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 0]
3 [0 1 0 0]
After adding edge 2-3:
Adjacency List:
0: 2 -> 1 -> null
1: 3 -> 0 -> null
2: 3 -> 0 -> null
3: 2 -> 1 -> null
Adjacency Matrix:
0 1 2 3
0 [0 1 1 0]
1 [1 0 0 1]
2 [1 0 0 1]
3 [0 1 1 0]