Sub topic 14
Where linked lists are used in practice
This chapter assumes you can write the singly and doubly linked list operations from earlier chapters and that you know Big-O notation at an introductory level. Here we look at where linked lists show up in real systems, and where they are the wrong choice.
What linked lists are good at
A linked list gives you two things an array does not:
- Insertion or removal at a known position in O(1), with no shifting of other elements.
- Stable nodes. Once a node exists, it never moves in memory, so other code can hold a reference to it safely.
Almost every practical use rests on one of these two properties.
Common uses
| Use | Why a linked list fits |
|---|---|
| Queue and deque | Add at one end and remove at the other in O(1) without shifting items |
| LRU cache | A doubly linked list reorders entries in O(1) when a given node is known |
| Undo history | Each state points to the previous one |
| Free lists in memory allocators | Free blocks link to each other, and the links live inside the blocks themselves |
| Hash table buckets | Colliding keys are chained in a short list |
| Kernel and OS structures | Linux uses intrusive doubly linked lists for tasks, and the nodes cannot move |
| Adjacency lists in graphs | Each vertex keeps a list of its neighbors |
Worked example: an LRU cache
A least-recently-used (LRU) cache keeps the most recent items and evicts the oldest when it is full. It needs two fast operations: find an item by key, and move an item to the "most recent" position.
A dictionary finds a node by key in O(1). A doubly linked list moves that node to the front in O(1), because the unlink function from the previous chapter needs only the node. Together they give O(1) for both get and put.
class DNode:
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):
self.capacity = capacity
self.map = {}
self.head = DNode() # sentinel: most recent side
self.tail = DNode() # sentinel: least recent side
self.head.next = self.tail
self.tail.prev = self.head
def _unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _push_front(self, node):
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.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.tail.prev
self._unlink(oldest)
del self.map[oldest.key]
node = DNode(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 the most recent
cache.put("c", 3) # evicts "b"
print(cache.get("b")) # None
print(cache.get("a")) # 1The two sentinel nodes remove the head and tail special cases, as in the sentinel chapter. Each node stores its own key so that eviction can delete the matching dictionary entry.
When not to use a linked list
Linked lists are often slower than arrays in practice, even when Big-O suggests otherwise.
- Array elements sit next to each other in memory, so the CPU cache loads several at once. Nodes are scattered, so each step can be a cache miss.
- Each node costs extra memory for its references and, in many languages, an allocation.
- Reaching the k-th element takes O(k). Arrays do it in O(1).
In Python, list is a dynamic array and collections.deque handles queue work. Rust's standard library documentation recommends Vec or VecDeque for most cases. Use a hand-built linked list when you need stable node references or O(1) splicing at known nodes, or when you are learning.
Common errors
- Choosing a linked list for "fast insertion" without noticing that finding the insertion point costs O(n).
- Forgetting to update the dictionary when a node is evicted, which leaves stale entries.
- Forgetting to update
headortailwhen removing an end node in a list without sentinels.
Exercise
In the LRU cache, why does each node store its key as well as its value?
Show answer
When the least recently used node is evicted from the end of the list, the code only has the node. It needs the node's key to delete the matching entry from the dictionary. Without the key, the dictionary would keep a stale reference.
Exercise
A program inserts and removes items in the middle of a sequence, but it always finds the position by searching by value first. Is a linked list a clear win over an array?
Show answer
No. The search costs O(n), which dominates the O(1) insertion. An array's shifting is also O(n), and its cache-friendly layout often makes it faster in practice. A linked list wins only when you already hold the node reference.