Tail pointers and doubly linked lists
After this: Say what a tail pointer and a prev pointer give you at both ends.
On this page · 6 sections · 4 checks
You have seen that adding at the front of a list is O(1), because head is a pointer you keep. Adding at the back is O(n), because you have to walk to the tail first. What if you kept a pointer to the tail as well?
This lesson adds two pointers to the list, one at a time. Each one removes a walk, and each one has a cost.
A tail pointer
Keep a second variable, tail, that always points at the last node. To add 9 to 3 → 5 → 7:
- Create a new node holding 9.
- Point the current tail, 7, at the new node.
- Move
tailto the new node.
That is two pointer writes and no walk, so appending is now O(1).
There is a cost. Every operation that changes the end of the list must also update tail. If one of them forgets, tail points at the wrong node.
One job stays slow: removing the last node. In 3 → 5 → 7, tail is on 7. To remove 7, you have to make 5 the new last node. But 7 cannot tell you where 5 is, because its pointer only goes forwards. The only way to find 5 is to walk from the head, and that is O(n).
A prev pointer
The problem is that a node knows what comes after it, but not what comes before it. In the treasure hunt, each clue says where the next clue is, but none says where you came from.
The fix is to give each node a second pointer, prev, to the node before it. In earlier lessons prev was a variable in a loop. Here it is a field in every node, but it means the same thing: the node before.
A list with only next pointers is called singly linked. A list with both is a . We draw it with arrows both ways: 3 ⇄ 5 ⇄ 7.
Now you can remove a node you hold, with no walk. To remove 5 from 3 ⇄ 5 ⇄ 7:
- Follow
prevfrom 5 to reach 3. Set thenextof 3 to 7. - Follow
nextfrom 5 to reach 7. Set theprevof 7 to 3.
The list is now 3 ⇄ 7. Both neighbours were one pointer away, so the length of the list does not matter.
Here is what the prev pointer gives you.
- Removing a node you hold is O(1).
- Inserting before a node you hold is O(1).
- Removing the last node is O(1), because
tail.previs the new last node. So withprevandtailtogether, adding and removing are O(1) at both ends. - You can walk backwards, which a singly linked list cannot do at all.
Here is what it costs.
- Every node stores one more pointer, so the list takes more memory.
- Every change writes more pointers. Inserting in the middle writes four pointers and not two: the new node's
prevandnext, and one pointer in each neighbour. Removing writes two and not one.
The code
class DNode: def __init__(self, value): self.value = value self.prev = None # the node before: the second pointer self.next = None
class DoublyLinkedList: def __init__(self): self.head = None self.tail = None # kept up to date, so the end is one pointer away
def append(self, value): # O(1): no walk to the end node = DNode(value) if self.tail is None: self.head = self.tail = node else: node.prev = self.tail self.tail.next = node self.tail = node
def remove(self, node): # O(1): prev is a pointer, not a walk if node.prev is None: self.head = node.next else: node.prev.next = node.next if node.next is None: self.tail = node.prev else: node.next.prev = node.prevclass DNode { int value; DNode prev; // the node before: the second pointer DNode next; DNode(int value) { this.value = value; }}
class DoublyLinkedList { DNode head; DNode tail; // kept up to date, so the end is one pointer away
void append(int value) { // O(1): no walk to the end DNode node = new DNode(value); if (tail == null) { head = tail = node; } else { node.prev = tail; tail.next = node; tail = node; } }
void remove(DNode node) { // O(1): prev is a pointer, not a walk if (node.prev == null) head = node.next; else node.prev.next = node.next; if (node.next == null) tail = node.prev; else node.next.prev = node.prev; }}Here is how to read it.
DNodeis a node with aprevfield as well asnext.DoublyLinkedListkeeps the two pointersheadandtail.appendfirst checks for an empty list. In that case the new node is both the head and the tail.- Otherwise
appenddoes three writes: the new node'sprevpoints at the old tail, the old tail'snextpoints at the new node, andtailmoves to the new node. There is no walk. removeis the reason for all of this. It finds both neighbours through the node you hold.removehas twoiftests for the ends of the list. If the node has noprev, it was the first node, soheadmoves. If it has nonext, it was the last node, sotailmoves.
d = DoublyLinkedList()for v in [3, 5, 7]: d.append(v) # three appends, no walkingmiddle = d.head.next # hold the node 5d.remove(middle) # two pointer writes, no walkprint(d.head.value, d.tail.value, d.head.next.value, d.tail.prev.value)3 7 7 3
DoublyLinkedList d = new DoublyLinkedList();for (int v : new int[] {3, 5, 7}) d.append(v); // three appends, no walkingDNode middle = d.head.next; // hold the node 5d.remove(middle); // two pointer writes, no walkSystem.out.println(d.head.value + " " + d.tail.value + " " + d.head.next.value + " " + d.tail.prev.value);3 7 7 3
Watch it happen
The visualizer's list has only next pointers and a head, so here you can see the walk that a tail pointer saves.
- Append 13Append 13 with only a head pointer. Watch the steps counter go up before the one write at the end.
- Prepend 1
Run an operation to begin.
The append walked five nodes and then made one write at the back. The prepend wrote two pointers and walked nowhere. With a tail pointer, an append needs no walk either.
Check yourself
A doubly linked list is 3 ⇄ 5 ⇄ 7. You hold the node 5. Which pointers change to remove it?
What does the prev pointer cost, compared with a list that has only next pointers?
A list has only next pointers in its nodes, and keeps both a head and a tail pointer. Which job is still O(n)?
Three appends, then the middle node is removed. What prints (head, tail, head.next, tail.prev)?
d = DoublyLinkedList()for v in [3, 5, 7]: d.append(v) # three appends, no walkingmiddle = d.head.next # hold the node 5d.remove(middle) # two pointer writes, no walkprint(d.head.value, d.tail.value, d.head.next.value, d.tail.prev.value)DoublyLinkedList d = new DoublyLinkedList();for (int v : new int[] {3, 5, 7}) d.append(v); // three appends, no walkingDNode middle = d.head.next; // hold the node 5d.remove(middle); // two pointer writes, no walkSystem.out.println(d.head.value + " " + d.tail.value + " " + d.head.next.value + " " + d.tail.prev.value);Connect
- Say what a tail pointer gives you: appending in O(1), with one more pointer to keep correct.
- Say what a prev pointer gives you: removing a node you hold in O(1), and walking backwards.
- Name the cost: a second pointer in every node, and about twice the pointer writes for each change.