Sub topic 4
Linked lists: when they help and when they do not
This chapter assumes you know Python lists and dictionaries, can read Big-O notation, and have read the previous chapter on arrays and dynamic lists. It covers what a linked list does well, what it does badly, and why Python code rarely needs one.
The working model
A linked list stores each item in its own small object called a node. Each node holds a value and a reference to the next node. A doubly linked list also keeps a reference to the previous node. The list itself holds a reference to the first node, called the head.
Nodes can sit anywhere in memory. Position is defined only by the chain of references. That one fact explains every cost below.
Operation costs
| Operation | Dynamic array (Python list) | Singly linked list |
|---|---|---|
| Read item at index i | O(1) | O(n), walk from head |
| Insert or delete at the front | O(n), shifts items | O(1) |
| Insert or delete at a known node | O(n), shifts items | O(1) |
| Find a value | O(n) | O(n) |
| Append at the end | O(1) amortized | O(1) only if you keep a tail reference |
The key phrase is "at a known node". Linked lists make an edit cheap only after you already hold a reference to the spot. Finding that spot still costs O(n), unless something else gives it to you.
A minimal implementation
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
class LinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
self.head = Node(value, self.head) # O(1)
def pop_front(self):
if self.head is None:
raise IndexError("pop from empty list")
value = self.head.value
self.head = self.head.next # O(1)
return value
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
items = LinkedList()
for name in ["alan", "grace", "ada"]:
items.push_front(name)
print(list(items)) # ['ada', 'grace', 'alan']
print(items.pop_front()) # adaFront insertion and removal touch only the head reference, so they never shift other items.
When a linked list helps
- You hold node references and edit near them often. An LRU cache is the standard case: a dictionary maps keys to nodes of a doubly linked list. A hit moves its node to the front in O(1), and eviction removes the tail in O(1).
- You need many splices or removals in the middle of a sequence, and you already have the nodes.
- You need stable references. A node never moves when its neighbors change. A Python list shifts items when you insert.
When it does not help
- You need random access by index. A list does this in O(1). A linked list walks the chain.
- You only need a queue.
collections.dequegives O(1) operations at both ends with less memory and better speed than hand-built nodes. - You iterate a lot. Each node is a separate object, so traversal follows scattered pointers. The memory layout chapter explains why this is slower than scanning a contiguous array, even at the same Big-O.
- Memory is tight. Every item pays for a node object plus a reference.
Common mistake: "O(1) insert" in the middle
Writing "linked lists insert in O(1)" without the qualifier is the usual error. If your code receives an index or a value, it must first search, so the whole operation is O(n). The array version is also O(n), and its shifting runs as fast native code. In practice the array often wins.
Exercise
You are building a cache that evicts the least recently used entry. Each lookup must move the accessed entry to the "most recent" end, and each eviction must remove the "least recent" end, both in O(1). Which combination of structures fits, and why does a plain Python list fail?
Show answer
Use a dictionary from key to node plus a doubly linked list ordered by recency. The dictionary finds the node in O(1), and the doubly linked list unlinks it and reinserts it at the front in O(1) because you already hold the node. A plain list needs O(n) to find or remove an item from the middle and O(n) to shift items when inserting at the front.
Exercise
A teammate says, "Use a linked list for this queue, since front removal is O(1)." What would you suggest instead in Python?
Show answer
Use collections.deque. It also gives O(1) removal at the front with popleft, and it is faster and smaller than a hand-written node chain.