8.2Graph with Adjacency Lists
Adding and removing edges
Adding an edge to a matrix meant writing 1 into a cell. In an adjacency list an edge is a node: adding it means linking a new node into a list, removing it means unlinking the node. Both are operations you did in the linked list lessons; here the vertex number only tells you which list to use.
- How a neighbour is inserted at its sorted place in the list
- How a repeated edge is caught during the same scan
- Why an undirected edge is written into two lists and removed from two lists
1The idea
addEdge(g, u, v) first makes the same checks as in the matrix: are the vertices valid, is u == v. Then it hands the work to the helper insertSorted(g, u, v). The helper walks the list of u with prev and temp and skips the values below v. If the value of temp where it stops is v, the edge is already there: false. Otherwise the new node is linked between prev and temp; if prev is NULL, the new node becomes the head of the list. This is the same as the insert at a position lesson.
If the graph is undirected, the same helper adds u to the list of v. Because the lists are kept sorted, the neighbours are always walked from smallest to largest, and BFS and DFS give the same order as the matrix version.
removeEdge looks for v in the list of u with removeFromList. If it is not found, it returns false. If it is, the node is unlinked as in the delete from the middle lesson: prev->next is joined to the node after the deleted one, and if the node was the head, adj[u] moves on. In C the node is freed. In an undirected graph the same work is repeated in the list of v.
2Step by step
In the drawing the sample graph is missing the edge between 1 and 4. First addEdge(&g, 1, 4) adds a node to two lists, then removeEdge(&g, 0, 3) removes a node from two lists. The name under a node is the pointer on it at that moment.
- Start: a graph with 6 edges. There is no edge between 1 and 4.
addEdge(&g, 1, 4). The vertices are valid.insertSorted(g, 1, 4)starts:previs NULL,tempis the head of the list of 1, 0.- 0 < 4: move on.
prevpoints to 0,tempto 2. - 2 < 4: move on.
prevpoints to 2 andtempbecame NULL. The loop stops; 4 is not in the list. - A new node 4 is made, its
nextistemp(NULL) andprev->nextis linked to it. The list of 1: 0 2 4. - The graph is undirected:
insertSorted(g, 4, 1).tempis the head of the list of 4, 3. 3 < 1 is false; the loop never runs andprevstays NULL. - The new node 1 is linked in front of 3, and since
previs NULL it becomesadj[4]. The list of 4: 1 3 5. The edge is in the graph. removeEdge(&g, 0, 3).removeFromList(g, 0, 3): in the list of 0, 1 ≠ 3, move on;tempfound 3,previs on 1.prev->next = temp->next: 1 now points to NULL. Node 3 is out of the list and is freed.- Undirected:
removeFromList(g, 3, 0). In the list of 3, 0 is found right at the head;previs NULL. - The deleted node was the head:
adj[3] = temp->next. The list of 3: 4. The edge between 0 and 3 is gone. - Result: 1 and 4 are neighbours, 0 and 3 are not. The lists are still sorted.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; bool insertSorted(struct Graph* g, int u, int v) { struct Node* prev = NULL; struct Node* temp = g->adj[u]; while (temp != NULL && temp->data < v) { // skip the ones below v prev = temp; temp = temp->next; } if (temp != NULL && temp->data == v) return false; // the edge is already there struct Node* node = malloc(sizeof(struct Node)); if (node == NULL) return false; node->data = v; node->next = temp; if (prev == NULL) g->adj[u] = node; // at the head of the list else prev->next = node; return true;} bool addEdge(struct Graph* g, int u, int v) { if (u < 0 || u >= g->n || v < 0 || v >= g->n || u == v) return false; if (!insertSorted(g, u, v)) return false; // it was already there if (!g->directed) insertSorted(g, v, u); // undirected: both lists return true;} bool removeFromList(struct Graph* g, int u, int v) { struct Node* prev = NULL; struct Node* temp = g->adj[u]; while (temp != NULL && temp->data != v) { prev = temp; temp = temp->next; } if (temp == NULL) return false; // there is no such edge if (prev == NULL) g->adj[u] = temp->next; else prev->next = temp->next; free(temp); return true;} bool removeEdge(struct Graph* g, int u, int v) { if (u < 0 || u >= g->n || v < 0 || v >= g->n) return false; if (!removeFromList(g, u, v)) return false; if (!g->directed) removeFromList(g, v, u); return true;}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 insertSorted(int u, int v) { Node prev = null; Node temp = adj[u]; while (temp != null && temp.data < v) { // skip the ones below v prev = temp; temp = temp.next; } if (temp != null && temp.data == v) return false; // the edge is already there Node node = new Node(v); node.next = temp; if (prev == null) adj[u] = node; // at the head of the list else prev.next = node; return true; } boolean addEdge(int u, int v) { if (u < 0 || u >= n || v < 0 || v >= n || u == v) return false; if (!insertSorted(u, v)) return false; // it was already there if (!directed) insertSorted(v, u); // undirected: both lists return true; } boolean removeFromList(int u, int v) { Node prev = null; Node temp = adj[u]; while (temp != null && temp.data != v) { prev = temp; temp = temp.next; } if (temp == null) return false; // there is no such edge if (prev == null) adj[u] = temp.next; else prev.next = temp.next; return true; } boolean removeEdge(int u, int v) { if (u < 0 || u >= n || v < 0 || v >= n) return false; if (!removeFromList(u, v)) return false; if (!directed) removeFromList(v, u); return true; }}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 insert_sorted(self, u, v): prev = None temp = self.adj[u] while temp is not None and temp.data < v: # skip the ones below v prev = temp temp = temp.next if temp is not None and temp.data == v: return False # the edge is already there node = Node(v) node.next = temp if prev is None: self.adj[u] = node # at the head of the list else: prev.next = node return True def add_edge(self, u, v): if not (0 <= u < self.n and 0 <= v < self.n) or u == v: return False if not self.insert_sorted(u, v): return False # it was already there if not self.directed: self.insert_sorted(v, u) # undirected: both lists return True def remove_from_list(self, u, v): prev = None temp = self.adj[u] while temp is not None and temp.data != v: prev = temp temp = temp.next if temp is None: return False # there is no such edge if prev is None: self.adj[u] = temp.next else: prev.next = temp.next return True def remove_edge(self, u, v): if not (0 <= u < self.n and 0 <= v < self.n): return False if not self.remove_from_list(u, v): return False if not self.directed: self.remove_from_list(v, u) return TrueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Adding and removing scan the list of the vertex: at most as many steps as its degree, O(d). Undirected, two lists are scanned: O(d(u) + d(v)).
Adding takes one node; removing gives one node back.
In the matrix the same operations were O(1). A list keeps only the neighbours that exist, so checking the order and repeats needs a scan. If order and repeats do not matter, the new node goes to the head and adding becomes O(1).
4Common mistake
A common mistake in an undirected graph is removing the edge from one list only:
bool removeEdge(struct Graph* g, int u, int v) { return removeFromList(g, u, v); // u is left in v's list}Then v is gone from the list of u, but u stays in the list of v. The graph is now neither directed nor undirected: BFS from v reaches u, BFS from u does not reach v. Another mistake in C is not freeing the node taken out; every removal leaks one node of memory.
5Try it
The list of 4 is 1 3 5. Where does insertSorted(g, 4, 2) put the new node?
The answer is B. 1 < 2, so it is skipped; 3 < 2 is false and the loop stops at 3. The new node goes between prev (1) and temp (3).
Show the answer
The answer is B. 1 < 2, so it is skipped; 3 < 2 is false and the loop stops at 3. The new node goes between prev (1) and temp (3).
In an undirected graph the list of 1 is 0 2 4 and the list of 4 is 1 3 5. What does addEdge(&g, 4, 1) return?
The answer is B. insertSorted(g, 4, 1) finds 1 in the list of 4 and returns false; addEdge returns false too and no list changes.
Show the answer
The answer is B. insertSorted(g, 4, 1) finds 1 in the list of 4 and returns false; addEdge returns false too and no list changes.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.