Sub topic 9
Doubly linked lists and tail pointers
This chapter assumes you can read basic Python, know what a reference is, and understand O(1) and O(n). It builds on the singly linked list from the earlier chapters. Here you will see why a singly linked list is awkward at its far end and in the middle, and how two additions fix that: a prev link on each node and a tail pointer on the list.
The weakness of a singly linked list
A singly linked node stores only a next reference. That makes two operations expensive even when you know where you want to work:
- Appending at the end. With only a
head, you must walk every node to find the last one. That is O(n). - Removing a node you already hold. To unlink node
x, you must change thenextof the node before it. You have no link back, so you walk from the head to find it. That is O(n).
Both costs come from missing information, not from the linked structure itself. Adding that information is cheap.
Tail pointers
A tail pointer is a second reference kept by the list object. It always points at the last node. With it, appending skips the walk:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
node = Node(value)
if self.tail is None: # empty list
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def to_list(self):
out = []
node = self.head
while node is not None:
out.append(node.value)
node = node.next
return out
lst = SinglyLinkedList()
for v in (1, 2, 3):
lst.append(v)
print(lst.to_list()) # [1, 2, 3]Appending is now O(1). The empty-list case is the usual source of bugs: when the list is empty, both head and tail must be set.
A tail pointer does not make removing the last node cheap in a singly linked list. To move tail back one node you still need the predecessor, which means a walk from the head.
Doubly linked nodes
A doubly linked list gives each node both next and prev. The node can now reach its neighbors in either direction. This is the code from the spine:
class DNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
def unlink(node):
if node.prev is not None:
node.prev.next = node.next
if node.next is not None:
node.next.prev = node.prev
node.prev = None
node.next = Noneunlink touches only the node and its two neighbors, so it is O(1) with no search. Compare this with the singly linked case, where finding the predecessor costs O(n).
Note the last two lines of unlink. They clear the removed node's own links so it does not keep stale references into the list.
Head and tail bookkeeping
unlink fixes the neighbors, but it does not know about the list object. If the removed node was the first or last node, head or tail still points at it. The caller must handle this:
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
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
return node
def remove(self, node):
if node is self.head:
self.head = node.next
if node is self.tail:
self.tail = node.prev
unlink(node)
def to_list(self):
out = []
node = self.head
while node is not None:
out.append(node.value)
node = node.next
return out
dll = DoublyLinkedList()
a = dll.append("a")
b = dll.append("b")
c = dll.append("c")
dll.remove(b)
dll.remove(c)
print(dll.to_list()) # ['a']
print(dll.tail.value) # aThe order matters. Update head and tail before calling unlink, because unlink clears node.prev and node.next, which you still need.
append returns the node on purpose. The O(1) removal only works if you keep a reference to the node. If you only know the value, you must search for it, and that is O(n).
Costs compared
| Operation | Array | Singly, head only | Singly with tail | Doubly with tail |
|---|---|---|---|---|
| Append at end | O(1) amortized | O(n) | O(1) | O(1) |
| Remove last | O(1) | O(n) | O(n) | O(1) |
| Remove a node you hold | O(n) shift | O(n) | O(n) | O(1) |
| Prepend | O(n) | O(1) | O(1) | O(1) |
The cost of the extra links is one more reference per node, so memory use rises. The next chapters weigh that against the speed gains.
Exercise
In a singly linked list that has both a head and a tail pointer, why is removing the last node still O(n), and what change makes it O(1)?
Show answer
To remove the last node, the new tail must be the node just before it. A singly linked node has no prev link, so you must walk from the head to find that predecessor, which is O(n). Making the list doubly linked gives the tail node a prev reference, so the new tail is found directly and removal is O(1).
Exercise
In DoublyLinkedList.remove, what goes wrong if you call unlink(node) first and then check node is self.tail and assign self.tail = node.prev?
Show answer
unlink sets node.prev and node.next to None. After that, self.tail = node.prev assigns None, so the list loses its real last node and tail no longer points into the list. The head and tail updates must read node.next and node.prev before unlink clears them.