Doubly linked lists: keeping prev and next in step
1 Why a node points back
In a singly linked list, each node holds a value and a next pointer, and we reach a node by walking from the head. The previous lesson built one and changed it.
That walk is the weak spot. To delete a node, we must change the next of the node before it. A singly list has no way back, so even when we already hold the node, we walk from the head to find its neighbour. That is O(n) for one delete. Walking the list backwards is not possible at all.
A train shows the fix. Each coach is coupled to the coach in front and the coach behind. A worker can take one coach out of the middle and couple its two neighbours, without walking down from the engine. A guard can walk the train in either direction.
A doubly linked list gives every node that second coupling. Next to next, each node has a prev pointer to the node before it.
2 The node and its one rule
Our running example is a train of four nodes, holding 3, 8, 5 and 6. Between each pair of neighbours there are two arrows. next points right, and prev points left.
The head's prev is null, because nothing comes before it. The tail's next is null. The node is the singly node with one more field:
C++
Why _Node. Browsers already have a built-in called Node, so the class takes another name.
Why Rc, RefCell and Weak. A node is pointed at from both sides, so it has two owners, and Rc allows that. RefCell lets us change a node through those shared pointers. prev is Weak, because two nodes that own each other would never be freed. Another common way is a Vec of nodes with prev and next stored as indexes.
The second pointer brings a duty. In the train, one coupling joins two coaches. In our list, each link is two pointers, one stored in each node. Here they are for every node:
| Node | prev | next |
|---|---|---|
| 3 | null | 8 |
| 8 | 3 | 5 |
| 5 | 8 | 6 |
| 6 | 5 | null |
Read any row next to its neighbour's row. 8's next is 5, and 5's prev is 8. That match is the rule every doubly linked list keeps:
The rule holds wherever the neighbour exists. Every operation must leave it true for every node it touched. A coupling with only one half fastened is the classic bug of this topic.
3 Taking a node out: two pointers
We hold node 8 and want it out. Its neighbours are 3 and 5, and we reach both from 8 itself: 8.prev and 8.next. No walk from the head is needed.
The drawings show each node as a row of three boxes, as in the table above: prev, val and next. A pointer box shows the value of the node it points to, and a dash means null.
Step 2 is the broken state. A walk forwards from the head reads 3, 5, 6. A walk backwards from the tail still reads 6, 5, 8, 3, because 5's prev still points at 8. Step 3 fixes the other half, and both walks agree again.
In the train, the worker joins coach 3 to coach 5 from both sides. Node 8 still points at its old neighbours, but nothing in the list points at it. It is out. Clearing its own two pointers is a good habit, so it cannot lead anyone back into the list.
So a delete is two assignments, and it takes O(1) time:
node.prev.next = node.next
node.next.prev = node.prev
4 Putting a node in: four pointers
Now we put a new node, 4, between 8 and 5. Both neighbours must point at it, and it must point at both of them. That is four pointers, and their order matters.
The same four assignments as code lines, with what each walk reads after each line:
| Line | Assignment | Forwards | Backwards |
|---|---|---|---|
| 1 | newNode.prev = before | 3 8 5 6 | 6 5 8 3 |
| 2 | newNode.next = after | 3 8 5 6 | 6 5 8 3 |
| 3 | before.next = newNode | 3 8 4 5 6 | 6 5 8 3 |
| 4 | after.prev = newNode | 3 8 4 5 6 | 6 5 4 8 3 |
Lines 1 and 2 change only the new node, so the list stays whole while we set them up. A new coach couples itself to both neighbours first, while the train still runs without it. Lines 3 and 4 then join the neighbours to it. Between lines 3 and 4, the list breaks the rule.
The safe habit is to save both neighbours in variables before changing anything. Here before is 8 and after is 5. Once they are saved, no assignment can lose them.
5 The head and the tail
At the ends of the list, one neighbour is missing. Then the two delete assignments change. Each case, on 3 ⇄ 8 ⇄ 5 ⇄ 6 and on a list of one node, 7:
| Delete | before | after | What changes |
|---|---|---|---|
| 8, in the middle | 3 | 5 | 3.next = 5, 5.prev = 3 |
| 3, the head | null | 8 | the head moves to 8, 8.prev = null |
| 6, the tail | 5 | null | 5.next = null, the tail moves to 5 |
| 7, the only node | null | null | the head becomes null |
Removing the engine is a different job from removing a middle coach. The head must move to the next node, so a delete function returns the new head. Inserting before the head is the same: the new node becomes the head, so the function returns it.
The code checks each neighbour before it uses it:
C++
Free it when you are done. The function does not delete the node, because a caller may want to put it back somewhere else. When nothing needs it any more, delete node.
Nothing to free. The garbage collector frees the node once nothing points to it.
Nothing to free. Python frees the node once nothing points to it.
Nothing to free. The garbage collector frees the node once nothing points to it.
Nothing to free. The garbage collector frees the node once nothing points to it.
Upgrade before use. A Weak pointer may point at a node that is gone, so upgrade() gives an Option. The node before is still in the list, so here it is always Some.
Nothing to free. The garbage collector frees the node once nothing points to it.
On our list, each delete reads the same both ways:
remove 8: 3 5 6 | backwards 6 5 3
remove 3: 8 5 6 | backwards 6 5 8
remove 6: 3 8 5 | backwards 5 8 3
remove 7 from [7]: empty
If the list also keeps a tail pointer, an else on the second if moves it to before, just as the first else moves the head.
6 Sentinels: a list with no ends
The ifs in that code exist only because the ends are different. A real train avoids the problem: the engine and the guard's van never leave it. Every passenger coach always has something coupled on both sides.
A list can do the same with two sentinel nodes, head and tail. They hold no value and are never removed. The real nodes sit between them, so the first real node is head.next.
Now every real node has both neighbours, so delete and insert lose their ifs. Delete is always two lines, and insert at the front is always four:
remove(node):
node.prev.next = node.next
node.next.prev = node.prev
addFront(node):
node.prev = head
node.next = head.next
head.next.prev = node
head.next = node
moveToFront(node):
remove(node)
addFront(node)
In addFront, the last two lines cannot swap. After head.next = node, the old first node is lost, and head.next.prev = node makes the node its own prev.
moveToFront is the heart of an LRU cache, a common design question. A map finds a key's node in O(1), and the list moves it to the front in O(1). The dummy node lesson later goes deeper into sentinels.
7 Mistakes and edge cases
- Fixing only one direction. Deleting 8 with only
3.next = 5prints 3 5 6 forwards, and the output looks right. Backwards it still reads 6 5 8 3. A problem that checks everyprevgives Wrong Answer. - Forgetting the head. Deleting 3 without moving the head returns the old head. The caller then prints a list that starts at a deleted node.
- Null at the ends. On the tail, 6,
node.nextis null, sonode.next.prev = node.previs a Runtime Error. The same goes fornode.prev.nexton the head. - Using a pointer after overwriting it. Inserting 4 before node 5, without saving
beforefirst, goes wrong in this order:
newNode.prev = node.prev // 8
newNode.next = node // 5
node.prev = newNode // 5.prev is now 4
node.prev.next = newNode // 4.next = 4, not 8.next = 4
The last line meant to reach 8, but node.prev is already 4. Node 4 now points to itself, and 8 never learns about it, so forwards still reads 3 8 5 6. Saving before at the start removes the problem.
8 Cost, and when to use it
A doubly linked list pays one extra pointer per node. In return, any node we hold can be removed or joined in O(1), and the list can be walked both ways.
| Operation | Array | Singly list | Doubly list |
|---|---|---|---|
| Read the k-th value | O(1) | O(n) | O(n) |
| Insert or delete at the front | O(n) | O(1) | O(1) |
| Delete a node we hold | O(n) | O(n) | O(1) |
| Delete the last value, with a tail pointer | O(1) | O(n) | O(1) |
| Extra space | none | n pointers | 2n pointers |
The train explains every row. Finding coach number k still means walking from one end, so reading the k-th value is O(n). Removing a coach we stand next to is O(1). The singly list cannot delete its last node fast even with a tail pointer, because it must find the node before the tail.
A problem needs one when it holds a node and must remove or move it fast, or when it must walk both ways:
- Removing or moving a node already found. An LRU cache keeps a map from key to node, and moves nodes around in O(1).
- Back and forward. A browser history or a text editor's cursor moves either way along a list.
- Two ends at once. In a sorted doubly linked list, one pointer can start at the head and one at the tail, as the two pointers lesson did with arrays.
next must point back to it, and its prev must point forward to it.Practice it
- Build a doubly linked list from an arrayMedium
- Insert before the headMedium
- Insert before the tailMedium
- Insert before the K-th nodeMedium
- Insert before a given nodeMedium
- Delete the headMedium
- Delete the tailMedium
- Delete the K-th nodeMedium
- Delete a given nodeMedium
- Reverse a doubly linked listMedium
- Delete every occurrence of a keyMedium
- Remove duplicates from a sorted doubly linked listMedium
- Pairs with a given sum in a doubly linked listMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.