8.2Graph with Adjacency Lists
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 adjacency list keeps only the edges that exist: every vertex has a linked list holding its neighbours. In this lesson you build the empty graph, a structure whose lists are all empty.
- How an adjacency list is built from an array and linked lists
- What the
adjarray insidestruct Graphholds - Why the empty graph is a structure whose lists are all NULL
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 undirected graph 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 directed graph 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.
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.
create(&g, 6, false)is called.nbecomes 6 anddirectedfalse. In C theadjarray holds random leftover addresses (?).i = 0:adj[0] = NULL. The list of 0 is empty.i = 1:adj[1] = NULL.i = 2:adj[2] = NULL.i = 3:adj[3] = NULL.i = 4:adj[4] = NULL.i = 5:adj[5] = NULL. The loop ends: 6 cells were written.- 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 listThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The loop writes each of the n cells once.
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 addressThe 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?
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.
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?
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.
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.