Linked lists
A linked list stores items in separate nodes, each pointing to the next one. Unlike an array, the nodes can live anywhere in memory. That makes inserting and removing at a known position O(1), but finding the k-th item O(n). Linked lists are a favourite interview topic because they test careful pointer handling.
head → [ 3 | •]→[ 7 | •]→[ 9 | •]→[ 4 | None ]A node and a list
| Operation | Array (Python list) | Singly linked list |
|---|---|---|
| Access k-th item | O(1) | O(n) |
| Insert/remove at the front | O(n) | O(1) |
| Insert/remove after a node you hold | O(n) | O(1) |
| Search | O(n) | O(n) |
| Memory | Compact | An extra pointer per item; scattered in memory (slower in practice) |
In everyday Python you'll rarely build one: list and collections.deque cover most needs. But linked structures are everywhere underneath: LRU caches, hash map buckets, file systems, and the trees and graphs later in this track.
The dummy (sentinel) node in remove is a trick worth remembering: it gives the head a "previous" node, so removing the first item needs no special case.
Reversing a list
The single most-asked linked list question. Walk the list once, turning each arrow around:
O(n) time, O(1) extra space for the loop (the recursive version uses O(n) stack space).
Fast and slow pointers
Move one pointer one step and another two steps at a time. This finds the middle in one pass, and detects cycles (Floyd's "tortoise and hare"):
If there's a cycle, the fast pointer laps the slow one and they meet; if not, the fast pointer reaches the end. O(n) time and O(1) memory, versus O(n) memory for remembering visited nodes in a set.
Merging two sorted lists
Doubly linked lists and an LRU cache
A doubly linked list has prev and next pointers, so you can remove any node in O(1) when you hold it. Combined with a hash map, it makes the classic LRU cache (keep the N most recently used items; evict the least recently used), where both get and put are O(1):
(Python's functools.lru_cache and collections.OrderedDict implement exactly this.)
Practice
- Write
is_palindrome(head)for a linked list in O(n) time and O(1) space (find the middle, reverse the second half, compare). - Find the node where two linked lists intersect.
- Add
peek_lru()to the LRU cache, returning the key that would be evicted next.
1.What does accessing the 1,000th item of a singly linked list cost?
2.How do fast and slow pointers detect a cycle?
3.Why does an LRU cache combine a hash map with a doubly linked list?