algoritmauzmanı
Sign in
TREN
8.2Graph with Adjacency Lists
Lesson 8.2.1

A graph of lists: creating it

The adjacency matrix set aside one cell for every pair of vertices; pairs with no edge took room as well. An keeps only the that exist: every vertex has a holding its neighbours. In this lesson you build the empty graph, a structure whose lists are all empty.

What you will learn
  • How an adjacency list is built from an array and linked lists
  • What the adj array inside struct Graph holds
  • Why the empty graph is a structure whose lists are all NULL
6 minTime O(n)Memory O(n)C · Java · Python

1Idea

The structure has two layers. Outside there is an array of n cells: adj[u] points to the first node of the list of vertex u. Each list has one node per neighbour; the data field of a node is the number of the neighbour vertex. The node is the same as in the linked list lessons: data and next.

In an every edge shows up in two lists: the edge between 1 and 4 is 4 in the list of 1 and 1 in the list of 4. So an undirected graph with e edges has 2e nodes in its lists. In a an edge is written only into the list of its source: e nodes.

create writes the number of vertices and the directed flag, then sets the first n lists to NULL: no vertex has a neighbour yet. In C this is a must, because the array may hold random leftover addresses, and a traversal would read them as nodes. In Java and Python a new array is already filled with null and None.

adjNULLNULLNULLNULLNULLNULL0123450123451?3?0?2?4?1?5?0?4?1?3?5?2?4?
The sample graph of this part and its adjacency lists. Each list is sorted from smallest to largest; the 7 edges are 14 nodes in the lists.

In this part the lists are kept sorted from the smallest number up. That way BFS and DFS written with lists walk in the same order as the matrix versions. Keeping them unsorted works too; then a new neighbour goes to the head of the list in O(1).

2Step by step

The drawing shows the graph on the left and the adj array on the right; the number under a cell is the vertex number. create(&g, 6, false) empties the lists one by one.

adj012345012345?0?1?2?3?4?51?3?0?2?4?1?5?0?4?1?3?5?2?4?
  1. create(&g, 6, false) is called. n becomes 6 and directed false. In C the adj array holds random leftover addresses (?).
  2. i = 0: adj[0] = NULL. The list of 0 is empty.
  3. i = 1: adj[1] = NULL.
  4. i = 2: adj[2] = NULL.
  5. i = 3: adj[3] = NULL.
  6. i = 4: adj[4] = NULL.
  7. i = 5: adj[5] = NULL. The loop ends: 6 cells were written.
  8. Result: a graph with 6 vertices and no edges. 6 pointers did the job of the matrix's 36 cells.

#define MAX 8 struct Node {    int data;                   // the number of the neighbour vertex    struct Node* next;}; struct Graph {    int n;                      // number of vertices    bool directed;              // true for a directed graph    struct Node* adj[MAX];      // adj[u]: head of u's neighbour list}; void create(struct Graph* g, int n, bool directed) {    g->n = n;    g->directed = directed;    for (int i = 0; i < n; i++)        g->adj[i] = NULL;       // every list starts empty}
class Node {    int data;           // the number of the neighbour vertex    Node next;    Node(int data) { this.data = data; }} class ListGraph {    int n;              // number of vertices    boolean directed;   // true for a directed graph    Node[] adj;         // adj[u]: head of u's neighbour list     ListGraph(int n, boolean directed) {        this.n = n;        this.directed = directed;        adj = new Node[n];      // Java starts every cell at null    }}
class Node:    def __init__(self, data):        self.data = data        # the number of the neighbour vertex        self.next = None class ListGraph:    def __init__(self, n, directed=False):        self.n = n              # number of vertices        self.directed = directed  # True for a directed graph        self.adj = [None] * n   # adj[u]: head of u's neighbour list

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

The loop writes each of the n cells once.

Memory
O(n)

An empty graph has only an array of n pointers. Every edge added brings one node (two in an undirected graph): O(n + e) in total.

The matrix held n² cells even for an empty graph. In sparse graphs the gap grows huge: a graph with 10,000 vertices and 30,000 edges needs 100 million matrix cells, but only 10,000 pointers and 60,000 nodes as lists.

4Common mistake

A common mistake in C is forgetting create and using the graph right away:

struct Graph g;g.n = 6;addEdge(&g, 0, 1);     // adj[0] is a random address

The adj array of the local variable g was never cleared. While walking the list of 0, addEdge takes a random address for a node, and the program crashes or reads garbage. Call create(&g, 6, false) first. The similar mistake in Python is starting with something like [Node] * n; an empty list is shown with None.

5Try it

An undirected graph has 5 vertices and 8 edges. How many nodes are there in its adjacency lists in total?

Show the answer

The answer is B. An undirected edge is written into two lists: 2 × 8 = 16 nodes. 25 is the number of cells in the matrix.

What does it mean if adj[3] is NULL?

Show the answer

The answer is B. The vertex exists (3 < n), but its list is empty: no edge is joined to 3. Other vertices may have edges.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.