DATA STRUCTURES PROGRAM • GRAPHS

Represent an Undirected Graph with Adjacency Lists

Learn how to represent an undirected graph with adjacency lists using a clear C program.

IntermediateAdjacency listLinked listUndirected graph

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0: 2 1
1: 3 0
2: 0
3: 1

COMPLETE C PROGRAM

Complete C implementation

dsa-graph-adjacency-list.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { int vertex; struct Node *next; };
void add_one(struct Node *graph[], int from, int to)
{
    struct Node *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->vertex = to; node->next = graph[from]; graph[from] = node;
}
void add_edge(struct Node *graph[], int first, int second)
{
    add_one(graph, first, second); add_one(graph, second, first);
}
void clear_graph(struct Node *graph[], int vertices)
{
    for (int vertex = 0; vertex < vertices; vertex++)
        while (graph[vertex] != NULL) {
            struct Node *removed = graph[vertex];
            graph[vertex] = removed->next; free(removed);
        }
}

int main(void)
{
    struct Node *graph[4] = {NULL};
    add_edge(graph, 0, 1); add_edge(graph, 0, 2); add_edge(graph, 1, 3);
    for (int vertex = 0; vertex < 4; vertex++) {
        printf("%d:", vertex);
        for (struct Node *node = graph[vertex]; node != NULL; node = node->next)
            printf(" %d", node->vertex);
        putchar('\n');
    }
    clear_graph(graph, 4);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0: 2 1
1: 3 0
2: 0
3: 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store each neighbour in the linked list owned by its source vertex.
  3. Display the computed result.

Store each neighbour in the linked list owned by its source vertex.

EFFICIENCY

Time and space complexity

Time complexity

O(V + E)

Auxiliary space

O(V + E)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.