Sub topic 10
Doubly linked lists
This chapter assumes you can write a singly linked list with push_front, append, and delete_value, and that you know why deleting needs the node before the target. It also assumes you know introductory Big-O.
What changes with a second reference
A doubly linked list node stores two references: next to the following node and prev to the preceding one. The list usually keeps both a head and a tail.
The extra reference gives you two abilities:
- You can walk backwards from the tail.
- You can remove a node in O(1) when you hold only that node. A singly linked list must first walk to the predecessor, which costs O(n).
The cost is one more reference per node, and every link change now touches two nodes.
A complete implementation
append is O(1) because the tail is stored. unlink takes the node itself. It repairs both neighbours and also updates head or tail when the node sat at an end.
class DNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
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 unlink(self, node):
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next
if node.next is not None:
node.next.prev = node.prev
else:
self.tail = node.prev
node.prev = None
node.next = None
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def reversed(self):
current = self.tail
while current is not None:
yield current.value
current = current.prev
items = DoublyLinkedList()
nodes = [items.append(v) for v in (1, 2, 3, 4)]
items.unlink(nodes[1]) # remove 2 from the middle
items.unlink(nodes[3]) # remove 4, the tail
print(list(items)) # [1, 3]
print(list(items.reversed())) # [3, 1]append returns the node on purpose. Code that keeps node handles, such as a cache that maps keys to nodes, can then call unlink directly without any search.
Common errors
- Updating only one direction. If you set
tail.next = nodebut forgetnode.prev = tail, forward traversal works and backward traversal silently skips or breaks. After any change, check thata.next is bimpliesb.prev is a. - Forgetting the ends. Unlinking the only node, the head, or the tail must update
headandtail. Theelsebranches inunlinkhandle this. - Wrong order of assignments. When inserting between
aandb, set the new node'sprevandnextfirst. Then changea.nextandb.prev. If you overwritea.nextfirst, you lose the reference tob. - Reference cycles and memory. In Python,
prevandnextform cycles between neighbours. The garbage collector handles this. Clearing the removed node's links, asunlinkdoes, stops a stale node from keeping its old neighbours reachable.
Trade-offs
| Operation | Singly linked | Doubly linked |
|---|---|---|
| Append (with tail stored) | O(1) | O(1) |
| Delete a given node | O(n) | O(1) |
| Walk backwards | Not possible | O(n) |
| Memory per node | One reference | Two references |
Use a doubly linked list when you need removal from the middle by handle, or traversal in both directions. Examples are an LRU cache or a text editor's cursor. Prefer a singly linked list when you only move forward and memory is tight.
Exercise
Write the four assignments that insert a new node n between existing nodes a and b, where a.next is b and b.prev is a, in an order that never loses a reference.
Show answer
n.prev = a; n.next = b; a.next = n; b.prev = n. The last two can be swapped, but n must have its own links set before either neighbour is changed, and neither neighbour should be repointed before you have read the other from a.next or b.prev.