Sub topic 14
Where linked lists are used in practice
This chapter assumes you can write the singly linked list from the earlier chapters. It also assumes you know the cost of insertion and deletion at a known position, the array comparison, and the idea of a doubly linked list. Here we look at where linked lists appear in real systems. We also look at why plain textbook linked lists are rarer than you might expect.
The honest picture
In everyday application code, you will seldom write a linked list yourself. Python's list is a dynamic array. Java's ArrayList is usually faster than LinkedList. Most Go and Rust code uses slices and vectors.
Linked lists still matter, for two reasons:
- Many systems are built on linked structures, and you will read or debug them.
- A linked list is the right choice in a few specific situations. It is the right choice when you hold a reference to a node and need to insert or remove there in O(1), without moving other elements.
Both reasons come from the same property. A node never moves in memory once it is created, and splicing only changes a few references.
Pattern 1: queues with O(1) at both ends
An array-backed queue has a problem. Removing from the front shifts every element, which costs O(n). A common fix is a circular buffer, but that needs a fixed or resizable capacity. A singly linked list with both a head and a tail reference avoids the problem. It enqueues at the tail and dequeues at the head, and both are O(1).
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, value):
node = Node(value)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.head is None:
raise IndexError("dequeue from empty queue")
value = self.head.value
self.head = self.head.next
if self.head is None:
self.tail = None
return value
q = Queue()
for v in (1, 2, 3):
q.enqueue(v)
print(q.dequeue(), q.dequeue()) # 1 2The tail reference is what makes append O(1). Compare it with the append method from the deletion chapter, which walked the whole list.
The easy bug is in dequeue. When the last node is removed, head becomes None, but tail still points at the removed node. The next enqueue would then attach to a dead node. Resetting tail fixes this.
Python's standard library offers collections.deque for this job. It is implemented as a doubly linked list of fixed-size blocks, not one node per element. That design is a compromise, and we return to it below.
Pattern 2: LRU caches
A least-recently-used (LRU) cache keeps a fixed number of entries. When it is full, it evicts the entry that has gone unused the longest. It needs three operations, all in O(1):
- Look up an entry by key.
- Move an entry to the "most recent" position.
- Remove the oldest entry.
A hash map gives O(1) lookup, and it can store a reference to the node for each key. A doubly linked list keeps the entries in recency order. Because the map hands you the node directly, you can unlink it in O(1). This is the unlink operation from the doubly linked list chapter. A singly linked list could not do this, because it would need the previous node and finding it costs O(n).
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: the node after it is most recent
self.tail = DNode() # sentinel: the node before it is least recent
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.prev = self.head
node.next = self.head.next
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 most recent
cache.put("c", 3) # evicts "b"
print(cache.get("b"), cache.get("a"), cache.get("c")) # None 1 3This example uses two sentinel nodes, as in the sentinel chapter. With a sentinel at each end, _unlink and _push_front never need to check for None, so there are no special cases for the ends of the list.
Each node stores its key. When the oldest node is evicted, you need the key to delete its entry from the map.
Python's collections.OrderedDict and functools.lru_cache use the same idea.
Pattern 3: chains inside other structures
Linked lists often sit inside a bigger structure, where you may not notice them.
| Where | How a linked list is used |
|---|---|
| Hash tables with chaining | Each bucket holds a list of entries whose keys hash to the same slot. |
| Memory allocators | Free blocks are linked together. The link is often stored inside the free block itself, so it costs no extra memory. |
| Operating system kernels | Linux uses intrusive circular doubly linked lists (`list_head`) for task lists, wait queues, and many other kernel objects. |
| Undo and redo history | A doubly linked list of states lets you step backward and forward and discard the redo branch. |
| Music or slideshow playlists | A circular list loops back to the start without any index arithmetic. |
| Adjacency lists in graphs | Each vertex keeps a list of its neighbors. Many implementations use arrays instead. |
| Functional languages | Lists in Haskell, OCaml, and Lisp are singly linked. Pushing at the front shares the rest of the list, so old versions stay valid. |
An intrusive list stores the prev and next references inside the object you want to track, instead of in a separate node object. The object can sit in several lists at once, and adding it to a list never allocates memory. This is common in C and in kernel code.
Why arrays often win anyway
Big-O analysis ranks linked lists well for splicing at a known node. Real hardware changes the picture:
- Cache locality. Array elements sit next to each other, so the CPU loads them in bulk. List nodes are scattered across memory, and every step to
nextrisks a cache miss. - Memory overhead. Every node pays for its reference or references. In Python, every node is also a full object with its own header.
- Allocation cost. One allocation per element is slower than growing one array occasionally.
- No random access. Reaching the i-th element costs O(i).
The costs below assume you already hold a reference to the node you act on.
| Operation | Singly linked | Doubly linked | Dynamic array |
|---|---|---|---|
| Insert at front | O(1) | O(1) | O(n) |
| Insert after known node | O(1) | O(1) | O(n) |
| Delete known node | O(n), needs previous node | O(1) | O(n) |
| Index access | O(n) | O(n) | O(1) |
| Append | O(1) with tail | O(1) with tail | O(1) amortized |
For small and medium sizes, an array usually beats a list even on operations where the list has the better big-O. This is why deque uses blocks. Each block is a small array, which keeps most of the locality, and the blocks are linked to give cheap growth at both ends.
Choosing a structure
Three questions settle most cases:
- Do you need to reach elements by position? If yes, use an array.
- Do you hold node references from somewhere else, such as a hash map? If yes, a doubly linked list gives O(1) removal.
- Is the main work only at the two ends? A deque or ring buffer is usually simpler and faster.
Common mistakes in applied code
- Forgetting the tail. A queue built on a list with only a
headmakes enqueue O(n). - Stale tail or head. Removing the last node must also reset
tail. Removing the first node of a single-node list must reset both ends. - Dangling map entries. In an LRU cache, evicting a node without deleting its key from the map leaves a reference to a removed node.
- Leaked links. After unlinking a node, set its own
prevandnexttoNone, asunlinkdoes in the doubly linked chapter. Otherwise stale references can keep other nodes alive, and later code can mistake the node for a member of the list. - Cycles from bad splicing. A wrong update in a circular or doubly linked list can create a loop. The cycle detection from the earlier chapter helps in tests.
Exercise
An LRU cache uses a hash map from key to node plus a linked list. Why must the list be doubly linked, and what would the cost of "move to front" become with a singly linked list?
Show answer
Moving a node to the front means unlinking it first, which requires updating the previous node's next reference. In a doubly linked list the node holds a prev reference, so the unlink is O(1). In a singly linked list you would have to walk from the head to find the previous node, which makes every get and put O(n) and removes the point of the cache.
Exercise
You need a structure for 10 million integers that are read mostly by index and rarely changed. A teammate suggests a linked list because "insertion is O(1)". Give two reasons the suggestion is weak.
Show answer
Index access is O(i) on a linked list, but the workload is mostly reads by index, which an array does in O(1). Each node also adds reference overhead and a separate allocation, and scattered nodes cause cache misses, so a 10-million-element list would use far more memory and traverse more slowly than an array. The O(1) insertion applies only at a known node, and the workload rarely inserts.