8.2Graph with Adjacency Lists
Neighbours and degree
In a matrix finding the neighbours of a vertex meant looking at all n cells of its row. In an adjacency list the neighbours are ready in a list: walking the list from start to end is enough. This lesson writes the same four functions with lists: are two vertices adjacent, the degree, the in-degree and printing the neighbours.
- How to print the neighbours by walking a list
- Why the degree is the length of the list
- Which operation is faster with lists and which with a matrix
1The idea
printNeighbors(g, u) starts temp at adj[u] and moves on with next until it is NULL, printing the value at each node. This is the same loop as in the traversing a linked list lesson. The list holds only neighbours, so no step is wasted: if 4 has three neighbours, three nodes are looked at.
degree counts the nodes in the same loop: the length of the list is the degree of the vertex. hasEdge(g, u, v) searches the list for v. In a matrix this meant looking at one cell; with a list, in the worst case the whole list is walked. This is the clearest difference between the two structures.
In a directed graph a list holds only the outgoing edges. Finding the edges coming into a vertex means scanning every list: inDegree looks for v in the list of every vertex. If the in-degree is asked for often, a second array of lists, the reversed edge lists, is kept.
2Step by step
In the drawing printNeighbors(&g, 4) walks the list of 4. temp is the node being looked at; the neighbours printed are green. The output is shown under the drawing.
printNeighbors(&g, 4)is called. The neighbours of 4 are in the listadj[4].temp = adj[4]: the first node is 1. 1 is printed. Output: 1.temp = temp->next: 3. It is printed. Output: 1 3.- The next node is 5. It is printed. Output: 1 3 5.
tempbecame NULL; the loop ends. Only 3 nodes were looked at.- Result: the neighbours of 4 are 1, 3 and 5.
degree(&g, 4)returns 3 with the same walk.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; bool hasEdge(struct Graph* g, int u, int v) { for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) if (temp->data == v) return true; return false;} int degree(struct Graph* g, int u) { int count = 0; for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) count++; // every node in the list is one edge return count;} int inDegree(struct Graph* g, int v) { int count = 0; for (int u = 0; u < g->n; u++) // look for v in every list for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) if (temp->data == v) count++; return count;} void printNeighbors(struct Graph* g, int u) { for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) printf("%d ", temp->data);}class Node { int data; Node next; Node(int data) { this.data = data; }} class ListGraph { int n; boolean directed; Node[] adj; ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; } boolean hasEdge(int u, int v) { for (Node temp = adj[u]; temp != null; temp = temp.next) if (temp.data == v) return true; return false; } int degree(int u) { int count = 0; for (Node temp = adj[u]; temp != null; temp = temp.next) count++; // every node in the list is one edge return count; } int inDegree(int v) { int count = 0; for (int u = 0; u < n; u++) // look for v in every list for (Node temp = adj[u]; temp != null; temp = temp.next) if (temp.data == v) count++; return count; } void printNeighbors(int u) { for (Node temp = adj[u]; temp != null; temp = temp.next) System.out.print(temp.data + " "); }}class Node: def __init__(self, data): self.data = data self.next = None class ListGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [None] * n def has_edge(self, u, v): temp = self.adj[u] while temp is not None: if temp.data == v: return True temp = temp.next return False def degree(self, u): count = 0 temp = self.adj[u] while temp is not None: count += 1 # every node in the list is one edge temp = temp.next return count def in_degree(self, v): count = 0 for u in range(self.n): # look for v in every list temp = self.adj[u] while temp is not None: if temp.data == v: count += 1 temp = temp.next return count def print_neighbors(self, u): temp = self.adj[u] while temp is not None: print(temp.data, end=" ") temp = temp.nextThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Printing the neighbours, counting the degree and searching for a neighbour take as long as the list: O(d). The in-degree scans every list: O(n + e).
Only temp and a counter are used.
In a matrix, finding the neighbours was always O(n) and the adjacency question O(1). With lists finding the neighbours is O(d) and the adjacency question O(d) too. Graph traversals rest on finding neighbours, so lists win on sparse graphs.
4Common mistake
A common mistake is losing the head while walking the list:
while (g->adj[u] != NULL) { printf("%d ", g->adj[u]->data); g->adj[u] = g->adj[u]->next; // the list is gone}This loop prints the neighbours correctly, but moves adj[u] forward at every step. When it ends, adj[u] is NULL: every edge of u looks deleted from the graph, and the nodes are left in memory with no owner. A walk is always done with a separate temp variable.
5Try it
In a graph with 1000 vertices, vertex 7 has 2 neighbours. With adjacency lists, how many nodes does degree(&g, 7) look at?
The answer is A. The list holds only the neighbours of 7: 2 nodes. The same question with a matrix scanned 1000 cells.
Show the answer
The answer is A. The list holds only the neighbours of 7: 2 nodes. The same question with a matrix scanned 1000 cells.
You keep a directed graph in adjacency lists. Which operation needs every list to be scanned?
The answer is B. A list holds only outgoing edges. The edges coming into a vertex are in the lists of other vertices; all of them must be checked.
Show the answer
The answer is B. A list holds only outgoing edges. The edges coming into a vertex are in the lists of other vertices; all of them must be checked.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.