Linked Lists, Part 2: Doubly Linked, Merge & LRU Cache
prev reference lets you delete a node in O(1) when you hold it. Merging two sorted lists is the merge step of merge sort. An LRU cache pairs a linked list with a hash map, and functools.lru_cache works the same way inside.After this lesson, you will be able to:
- Implement a doubly linked list with prev and next references and O(1) deletion of any node you hold
- Merge two sorted linked lists in O(n + m) with O(1) extra space using a dummy head
- Build a complete LRU cache from a doubly linked list and a dict, with O(1) get and put
- Reverse a linked list recursively and understand why iterative reversal usually wins
Before you start
#Doubly Linked List: The Killer Pointer
prev reference to each node. It points at the node before. That allows walking backwards and, far more importantly, deleting a node in O(1) when you hold that node directly.from __future__ import annotations
from typing import Any, Iterator, Optional
class DoublyNode:
"""Node for a doubly linked list. It knows both neighbors."""
def __init__(self, data: Any) -> None:
self.data = data
self.prev: Optional[DoublyNode] = None
self.next: Optional[DoublyNode] = None
def __repr__(self) -> str:
return f"DoublyNode({self.data!r})"
class DoublyLinkedList:
"""
Doubly linked list.
Key advantage over singly: O(1) deletion given the node itself,
and O(1) tail deletion without needing to re-find the new tail.
Python's collections.deque is a doubly linked list of fixed-size blocks.
"""
def __init__(self) -> None:
self.head: Optional[DoublyNode] = None
self.tail: Optional[DoublyNode] = None
self._size: int = 0
def append(self, data: Any) -> DoublyNode:
"""Add to end. Returns the new node (caller can cache for O(1) removal)."""
node = DoublyNode(data)
if self.tail is None:
self.head = self.tail = node
else:
node.prev = self.tail
self.tail.next = node
self.tail = node
self._size += 1
return node
def prepend(self, data: Any) -> DoublyNode:
"""Add to front. O(1)."""
node = DoublyNode(data)
if self.head is None:
self.head = self.tail = node
else:
node.next = self.head
self.head.prev = node
self.head = node
self._size += 1
return node
def remove_node(self, node: DoublyNode) -> None:
"""
Remove a specific node in O(1).
This is the main strength of a doubly linked list. You must hold
the node itself (not search for it). The LRU cache uses it.
"""
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next # node was the head
if node.next is not None:
node.next.prev = node.prev
else:
self.tail = node.prev # node was the tail
node.prev = node.next = None # drop the old links so the node can be freed
self._size -= 1
def pop_front(self) -> Any:
"""Remove and return front value. O(1)."""
if self.head is None:
raise IndexError("pop from empty list")
value = self.head.data
self.remove_node(self.head)
return value
def pop_back(self) -> Any:
"""Remove and return back value. O(1). A singly linked list needs an O(n) walk for this."""
if self.tail is None:
raise IndexError("pop from empty list")
value = self.tail.data
self.remove_node(self.tail)
return value
def __len__(self) -> int:
return self._size
def __str__(self) -> str:
"""Forward traversal: '1 <-> 2 <-> 3'"""
parts = []
current = self.head
while current is not None:
parts.append(str(current.data))
current = current.next
return " <-> ".join(parts) if parts else "empty"
def backward_str(self) -> str:
"""Backward traversal using the prev references."""
parts = []
current = self.tail
while current is not None:
parts.append(str(current.data))
current = current.prev
return " <-> ".join(parts) if parts else "empty"
def __iter__(self) -> Iterator[Any]:
current = self.head
while current is not None:
yield current.data
current = current.next#Doubly Linked List in Practice
dll = DoublyLinkedList()
n1 = dll.append(10)
n2 = dll.append(20)
n3 = dll.append(30)
print(dll) # 10 <-> 20 <-> 30
print(dll.backward_str()) # 30 <-> 20 <-> 10
# O(1) removal of the middle node: we hold the node itself
dll.remove_node(n2)
print(dll) # 10 <-> 30
# O(1) tail pop
val = dll.pop_back()
print(val) # 30
print(dll) # 10`append` returns the node it created, which is unusual — most append methods return None. What is that return value for?
A test suite removes a middle node with remove_broken, then asserts the forward traversal and the length are both correct. Does the suite go red?
#Sentinel Nodes: Eliminating Edge Cases
if self.head is None from insertion and deletion. Many implementations use two sentinels, one at each end, and the LRU cache below does. Then every insertion and deletion happens between two existing nodes, with no boundary branching at all. CPython's collections.deque does it differently: it links blocks of 64 items and tracks indexes inside the end blocks.#Merge Two Sorted Linked Lists
from typing import Optional
class Node:
def __init__(self, data):
self.data = data
self.next: Optional[Node] = None
def merge_sorted_iterative(l1: Optional[Node], l2: Optional[Node]) -> Optional[Node]:
"""
Merge two sorted linked lists into one sorted list.
O(n + m) time, O(1) space (it only rewires references).
"""
# The dummy head removes a special case. We return dummy.next at the end
dummy = Node(0)
current = dummy
while l1 is not None and l2 is not None:
if l1.data <= l2.data:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
# Attach whichever list still has nodes remaining
current.next = l1 if l1 is not None else l2
return dummy.next
def merge_sorted_recursive(l1: Optional[Node], l2: Optional[Node]) -> Optional[Node]:
"""Recursive version. Shorter, but O(n + m) stack space."""
if l1 is None:
return l2
if l2 is None:
return l1
if l1.data <= l2.data:
l1.next = merge_sorted_recursive(l1.next, l2)
return l1
else:
l2.next = merge_sorted_recursive(l1, l2.next)
return l2dummy.next at the end. Using a dummy node to remove the first-element special case comes up constantly in linked list problems.The loop ends with `current.next = l1 if l1 is not None else l2`, a single line with no loop. Why is that enough to attach everything left over?
#Reverse a Linked List (Recursive)
Part 1 reversed a list with a loop and three variables. Here is the same job done with recursion, a function that calls itself on a smaller list. It is short, but it uses O(n) call stack space.
def reverse_recursive(head: Optional[Node]) -> Optional[Node]:
"""
Recursive reversal. Elegant but uses O(n) call stack space.
Base case: empty list or single node — already reversed.
"""
if head is None or head.next is None:
return head
# Recursively reverse everything after head
new_head = reverse_recursive(head.next)
# head.next still points to the old second node.
# Make that node point back to head, then cut head's forward link.
head.next.next = head
head.next = None
return new_headRecursionError on a long list (the default limit is 1000 calls). Use the recursive version only when the surrounding code is already recursive and the list is short.In reverse_recursive, what goes wrong if you delete the line head.next = None?
#LRU Cache: A Real Caching Problem
functools.lru_cache works this way, and other caches use the same idea with different internals. It combines two data structures:- A doubly linked list keeps the entries in order, from most recently used (MRU) at the head to least recently used (LRU) at the tail. Moving a node to the front and evicting the tail are both O(1).
- A hash map (
dict) maps each cache key to its node in the list, so a lookup is O(1).
get and O(1) put, with automatic eviction.class DoublyNode:
"""LRU cache node. It stores key AND value (the key is needed to clean up the dict on eviction)."""
def __init__(self, key, value):
self.key = key
self.value = value
self.prev: Optional[DoublyNode] = None
self.next: Optional[DoublyNode] = None
class LRUCache:
"""
Least-Recently-Used cache with O(1) get and put.
Uses a doubly linked list (most-recent at head, least-recent at tail)
plus a dict (key -> node) for O(1) lookups. The list provides O(1)
move-to-front on access and O(1) eviction of the tail.
Two sentinel nodes (head and tail dummies) eliminate all boundary checks.
"""
def __init__(self, capacity: int) -> None:
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.cache: dict = {} # key -> DoublyNode
# Sentinels never hold real data and are always present
self._head = DoublyNode(None, None) # MRU side
self._tail = DoublyNode(None, None) # LRU side
self._head.next = self._tail
self._tail.prev = self._head
def _remove(self, node: DoublyNode) -> None:
"""Unlink a node from the list. O(1), because both neighbors exist (sentinels)."""
node.prev.next = node.next
node.next.prev = node.prev
def _add_to_front(self, node: DoublyNode) -> None:
"""Insert node right after the head sentinel (the MRU slot). O(1)."""
node.prev = self._head
node.next = self._head.next
self._head.next.prev = node
self._head.next = node
def get(self, key) -> int:
"""O(1). Returns -1 if key missing. Touching a key marks it most recent."""
if key not in self.cache:
return -1
node = self.cache[key]
# Move to front: unlink, then re-insert at head
self._remove(node)
self._add_to_front(node)
return node.value
def put(self, key, value) -> None:
"""O(1). Updates existing or inserts new; evicts LRU if over capacity."""
if key in self.cache:
# Update value and move to front
node = self.cache[key]
node.value = value
self._remove(node)
self._add_to_front(node)
return
if len(self.cache) >= self.capacity:
# Evict the LRU (just before the tail sentinel)
lru = self._tail.prev
self._remove(lru)
del self.cache[lru.key]
node = DoublyNode(key, value)
self.cache[key] = node
self._add_to_front(node)
# Demo
cache = LRUCache(capacity=3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
print(cache.get("a")) # 1: touches 'a' and moves it to the front. Order: a, c, b
cache.put("d", 4) # capacity full; evict LRU which is 'b'
print(cache.get("b")) # -1 (evicted)
print(cache.get("d")) # 4key as well as value? When we evict the LRU node, we must remove its entry from the cache dict too. The dict maps key to node, but eviction starts from the node at the tail. Without node.key we would have to scan the whole dict to find which key owns that node, which is O(n). Storing the key on the node keeps eviction O(1).The LRU cache carries a dict AND a doubly linked list. Why is neither structure enough on its own?
collections.OrderedDict does the same job in a few lines. Call move_to_end(key) on every hit and popitem(last=False) to evict the oldest entry. The collections module lesson shows the full version. Writing the linked list yourself, as above, is what shows why each step is O(1).Real-world uses
- Undo and redo: a doubly linked list of application states. Move back with
prevand forward withnext. - A music playlist that repeats: a circular linked list where
tail.next = head, so "next song" always works. - Browser history: the back button follows
prevand the forward button followsnext. - A memory allocator: its free list is a linked list of the blocks of memory that are available.
#Code Playground: Build It Yourself
Tests: assert cache.get(3) == 300; assert cache.get(2) == -1
#Key Takeaways
- Doubly linked lists exist so that you can delete any node you hold in O(1). LRU caches, undo and redo, and some operating system lists use this.
- Sentinel nodes at both ends remove boundary cases. Every insert and delete happens between two existing nodes.
- A dummy head makes merging sorted lists simple. The merge runs in O(n + m) and the first element needs no special case.
- An LRU cache is a doubly linked list plus a dict. The list keeps the order, the dict gives O(1) lookup, and the node stores the key so eviction can clean up the dict.
- Recursive reversal is short, but a loop is better in practice. Python's recursion limit of 1000 makes recursion risky on long lists.
You have a doubly linked list and you hold a direct reference to node C (in the middle). What is the time complexity of removing C from the list?