Sub topic 10
Doubly Linked Lists
This chapter assumes you can write a singly linked list with Node, head, traversal, insertion, and deletion. It also assumes you know Big-O notation at an introductory level. By the end you should be able to implement a doubly linked list, explain why it can remove a node in constant time, and pick between singly and doubly linked designs.
What changes when nodes point both ways
A singly linked node stores a value and a next reference. A doubly linked node adds a second reference, prev, which points to the node before it. The list usually keeps two entry points: head for the first node and tail for the last.
The second reference adds two abilities:
- You can walk the list backward, from
tailtohead. - A node can reach its own predecessor. Singly linked deletion has to find the predecessor by walking from the head, and a node in a doubly linked list already knows it.
The price is one extra reference per node and more pointer updates on every change.
The node and the list
The node is the same as in the singly linked case, with one more field.
class DNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = NoneThe list class tracks head, tail, and size. Keeping tail is what makes push_back constant time. A singly linked list without a tail has to walk the whole chain to append.
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def push_front(self, value):
node = DNode(value)
node.next = self.head
if self.head is not None:
self.head.prev = node
else:
self.tail = node
self.head = node
self.size += 1
return node
def push_back(self, value):
node = DNode(value)
node.prev = self.tail
if self.tail is not None:
self.tail.next = node
else:
self.head = node
self.tail = node
self.size += 1
return node
def insert_after(self, node, value):
new = DNode(value)
new.prev = node
new.next = node.next
if node.next is not None:
node.next.prev = new
else:
self.tail = new
node.next = new
self.size += 1
return new
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
self.size -= 1
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def iter_backward(self):
current = self.tail
while current is not None:
yield current.value
current = current.prev
items = DoublyLinkedList()
a = items.push_back(1)
b = items.push_back(2)
c = items.push_back(3)
items.unlink(b)
print(list(items)) # [1, 3]
items.insert_after(a, 2)
items.push_front(0)
print(list(items)) # [0, 1, 2, 3]
print(list(items.iter_backward())) # [3, 2, 1, 0]push_front, push_back, and insert_after return the new node. That return value matters, as the next section explains.
Why deletion becomes O(1)
In a singly linked list, delete_value stops at the node before the target so that node's next can skip over the target. Finding that predecessor means walking from the head, so deleting a node you already hold still costs O(n).
In a doubly linked list, the node carries its own predecessor. Deletion needs only the node:
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 = NoneThis version bypasses the node and clears its own links. It does not update a list's head or tail. The unlink method in the class above handles those cases.
The constant time applies when you already hold a reference to the node. Finding a node by value is still a walk, so delete_value on a doubly linked list remains O(n). The speedup comes from keeping node references, as the a, b, and c variables do in the example. You normally get such references from a hash map or from earlier operations.
The four cases of unlink
Each if and else in unlink covers a position:
| Position of the node | `prev` is None | `next` is None | What must be updated |
|---|---|---|---|
| Middle | no | no | the neighbors' `next` and `prev` |
| Head | yes | no | `head`, and `next.prev` |
| Tail | no | yes | `tail`, and `prev.next` |
| Only node | yes | yes | both `head` and `tail` become None |
If you forget the head or tail update, the list keeps a reference to a node that is no longer in it. Iteration then returns stale values, or push_back attaches to a detached node. Both bugs are silent.
Inserting in the middle: order matters
Inserting a node between node and node.next changes four references: new.prev, new.next, node.next.prev, and node.next. Set the new node's references first, using the old neighbors. Then rewire the neighbors.
If you set node.next = new first, you lose the only reference to the old successor, and the later lines read the wrong node. A safe habit is to write down the neighbors in local variables (before, after) and then make the four assignments.
def insert_between(before, after, value):
new = DNode(value)
new.prev = before
new.next = after
if before is not None:
before.next = new
if after is not None:
after.prev = new
return newThis helper links only the three nodes involved. A list class would still update head, tail, and size.
Sentinel nodes make it shorter
The four-case table is the same edge-case problem you met with the singly linked head. A sentinel node removes it here too. Use one dummy node whose next is the first real node and whose prev is the last real node. The list becomes circular through the sentinel, so every real node always has a non-None prev and next.
class SentinelList:
def __init__(self):
self.sentinel = DNode(None)
self.sentinel.next = self.sentinel
self.sentinel.prev = self.sentinel
def insert_after(self, node, value):
new = DNode(value)
new.prev = node
new.next = node.next
node.next.prev = new
node.next = new
return new
def push_back(self, value):
return self.insert_after(self.sentinel.prev, value)
def push_front(self, value):
return self.insert_after(self.sentinel, value)
def unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
def __iter__(self):
current = self.sentinel.next
while current is not self.sentinel:
yield current.value
current = current.next
s = SentinelList()
s.push_back(2)
s.push_front(1)
s.push_back(3)
print(list(s)) # [1, 2, 3]There are no if checks in insert_after or unlink. An empty list is a sentinel pointing at itself. The cost is one extra node and a different loop condition. Iteration stops when it returns to the sentinel, not when it reaches None. Never call unlink on the sentinel itself.
Costs compared with singly linked lists
| Operation | Singly linked | Doubly linked |
|---|---|---|
| Push at front | O(1) | O(1) |
| Push at back | O(n), or O(1) with a tail | O(1) with a tail |
| Pop from front | O(1) | O(1) |
| Pop from back | O(n) | O(1) |
| Delete a node you hold | O(n) | O(1) |
| Find by value | O(n) | O(n) |
| Walk backward | not possible | O(n) |
| Memory per node | value and one reference | value and two references |
Popping from the back is the clearest difference. A singly linked list with a tail still cannot move the tail backward without walking from the head. A doubly linked list sets tail = tail.prev in constant time.
Failure modes and gotchas
- Broken symmetry. The invariant is that
a.next is bexactly whenb.prev is a. Any update that changes only one direction breaks it. Traversal in one direction then looks fine while the other direction skips or repeats nodes. When debugging, write a checker that walks forward and verifies eachprev. - Stale node references. After
unlink, the node is no longer in the list. If you callunlinkon it a second time, itsprevandnextare both None, so the code treats it as the only node and wrongly resetsheadandtailto None. Track membership if callers might unlink twice. - Reference cycles. Each adjacent pair of nodes refers to each other. In Python the cyclic garbage collector can reclaim them, but clearing
prevandnextinunlink, as done above, releases memory sooner and avoids dangling links. In languages with reference counting, such as Rust'sRc, the backward link is usually a weak reference. - Cache behavior. Nodes are scattered in memory, so traversal is slower in practice than the Big-O suggests, and the extra reference makes each node larger. For a small list that is scanned often, an array is usually faster.
Where doubly linked lists are used
The best-known use is an LRU cache. A hash map maps each key to its node, and a doubly linked list orders the nodes by recent use. On a hit, the cache unlinks the node and pushes it to the front, both in O(1). On eviction it removes the tail node. Neither step works in constant time without prev.
Other uses include a text editor's cursor movement, browser history with back and forward, and undo and redo stacks. Python's collections.deque is built as a doubly linked list of fixed-size blocks, which keeps O(1) operations at both ends while reducing the per-element overhead.
Summary
- A doubly linked node has
prevandnext, and the list keepsheadandtail. - Given a node, you can unlink it in O(1), because the node knows both neighbors.
- Insertion and deletion must update both directions, and the order of assignments matters.
- A circular sentinel removes the head and tail special cases.
- The cost is an extra reference per node and more code to keep the two directions consistent.
Exercise
In the SentinelList above, write a method pop_back that removes and returns the last value, or returns None if the list is empty. Why does it need no special case for a list with one element?
Show answer
def pop_back(self): last = self.sentinel.prev; if last is self.sentinel: return None; value = last.value; self.unlink(last); return value. With one element, last.prev is the sentinel and last.next is the sentinel, so unlink sets sentinel.next to sentinel and sentinel.prev to sentinel. The list returns to its empty state through the same two assignments used for any middle node, so no head or tail branch is needed.
Exercise
A doubly linked list holds nodes A, B, and C in that order. You call unlink(B) with the class version, then call unlink(B) again. What happens on the second call, and how could you guard against it?
Show answer
After the first call, B.prev and B.next are None. On the second call both checks see None, so head is set to B.next (None), tail is set to B.prev (None), and size is decremented. The list is wrongly emptied even though A and C remain linked to each other. To guard against it, keep a flag or a reference to the owning list on each node, set it in insertion and clear it in unlink, and refuse to unlink a node that is not currently a member.