Course contentsShow
← C
Lesson 1041 of 1,21914. Data Structures in CFree lesson

Adjacency List implementation

Adjacency List implementation

What you'll learn: How to represent a graph efficiently in memory by using an array of linked lists to store connections between nodes.

The Post Office Analogy

In the previous lesson, we looked at Adjacency Matrices—big grids that mark every possible connection with a 1 or 0. While simple, they waste a lot of space if most nodes aren't connected.

Think of an Adjacency List like a row of mailboxes at an apartment complex. Each mailbox represents a vertex (node) in your graph. Inside vertex A's mailbox, there is a list of names of everyone A is friends with. If A is friends with B and C, you just drop two slips of paper in A's box. You don't need a giant chart of every person in the building; you only keep track of the actual relationships that exist.

Structuring the List

To build this in C, we need two components:

  1. A Node struct: This represents a neighbor. It contains the neighbor's ID and a pointer to the "next" neighbor in the list.
  2. A Graph struct: This contains an array where each index represents a vertex. Each element in the array is a pointer to the head of a linked list.

Implementation in C

Here is how we define the structures and add an edge between two vertices:

#include <stdio.h>
#include <stdlib.h>

// A node in the adjacency list
struct Node {
    int vertex;
    struct Node* next;
};

// The Graph structure
struct Graph {
    int numVertices;
    struct Node** adjLists; // An array of pointers to Nodes
};

// Create a new node
struct Node* createNode(int v) {
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->vertex = v;
    newNode->next = NULL;
    return newNode;
}

// Add an edge (for an undirected graph)
void addEdge(struct Graph* graph, int s, int d) {
    // Add edge from source (s) to destination (d)
    struct Node* newNode = createNode(d);
    newNode->next = graph->adjLists[s];
    graph->adjLists[s] = newNode;

    // Add edge from d to s (because the graph is undirected)
    newNode = createNode(s);
    newNode->next = graph->adjLists[d];
    graph->adjLists[d] = newNode;
}

Why use this?

Adjacency lists are the "gold standard" for sparse graphs (graphs where most nodes aren't connected to each other). Instead of using V2V^2 space (like a matrix), you only use enough memory to store the vertices and the edges that actually exist. This makes it much faster to answer the question, "Who are all of Vertex A's neighbors?" because you just iterate through a short list rather than checking an entire row of a giant grid.

Key takeaway

An Adjacency List is an array of linked lists, providing a memory-efficient way to store graph connections by only recording edges that exist.