Sub topic 12
Where these lists are used
This chapter assumes you have read the earlier chapters on doubly linked lists, circular lists, and sentinel nodes. You should be comfortable with prev/next pointers and with O(1) removal of a node you already hold.
Matching the variant to the job
Each variant exists because one operation is expensive in a plain singly linked list. Pick the variant that makes your hot operation cheap.
| Use case | Needs | Best fit |
|---|---|---|
| LRU cache | Remove from the middle, add at the front, evict at the back, all in O(1) | Doubly linked list with a sentinel, plus a hash map |
| Deque | Push and pop at both ends | Doubly linked list with head and tail |
| Round-robin scheduler | Cycle through items forever, with occasional insert or remove | Circular list |
| Playlist with repeat | Move forward and backward, wrap at the ends | Circular doubly linked list |
LRU cache
A least-recently-used (LRU) cache keeps a fixed number of entries. When it is full, it discards the entry that was used longest ago.
A hash map finds an entry in O(1), but it keeps no usage order. The list supplies the order. The most recently used entry sits next to the sentinel on the next side, and the least recently used entry sits on the prev side. The map stores the node for each key, so a hit can unlink that node directly. That unlink is O(1) only because each node has a prev pointer.
class _Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("capacity must be at least 1")
self.capacity = capacity
self.map = {}
self.sentinel = _Node()
self.sentinel.prev = self.sentinel
self.sentinel.next = self.sentinel
def _unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _push_front(self, node):
node.prev = self.sentinel
node.next = self.sentinel.next
self.sentinel.next.prev = node
self.sentinel.next = node
def get(self, key):
node = self.map.get(key)
if node is None:
return None
self._unlink(node)
self._push_front(node)
return node.value
def put(self, key, value):
node = self.map.get(key)
if node is not None:
node.value = value
self._unlink(node)
self._push_front(node)
return
if len(self.map) >= self.capacity:
oldest = self.sentinel.prev
self._unlink(oldest)
del self.map[oldest.key]
node = _Node(key, value)
self.map[key] = node
self._push_front(node)
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a") # "a" is now most recent
cache.put("c", 3) # evicts "b"
print(cache.get("b")) # None
print(cache.get("a")) # 1The sentinel removes every empty-list branch. _unlink and _push_front contain no if statements, and eviction reads sentinel.prev without checking for an empty list. The capacity check in __init__ matters. With capacity 0, sentinel.prev would be the sentinel itself, and eviction would try to remove it.
Each node stores its key as well as its value. When you evict the oldest node, you need its key to delete the map entry.
Deque
A deque (double-ended queue) supports push and pop at both ends. A doubly linked list with head and tail references does all four in O(1). A singly linked list cannot pop from the tail in O(1), because it must find the second-to-last node first.
Python's collections.deque does not use a node-per-item list. It stores items in linked blocks of 64 slots, which uses less memory and has better cache behavior. Write your own linked deque when you need to hold node references, for example to remove an item from the middle.
Round-robin scheduling
A round-robin scheduler gives each task a time slice in turn, then moves to the next task. A circular list fits this. The scheduler never reaches the end, because after the last task the cycle continues at the first.
With the tail-only design from earlier, rotate() advances to the next task in O(1). Adding a task is also O(1) at the position just behind the current one.
Common errors
- Evicting from the list but forgetting to delete the map entry. The cache then returns a node that is no longer in the list.
- Storing only the value in each node, so eviction cannot find the key to remove.
- Using a circular list but writing
while node is not None. That loop never ends.
Exercise
In the LRU cache above, why does the map store nodes instead of values, and what would get cost if it stored values and searched the list for the key?
Show answer
Storing nodes lets get unlink the node in O(1), because the node already holds its prev and next pointers. If the map stored values, get would have to walk the list to find the node, which costs O(n) and removes the point of using the map.