Linked lists: pointers, reversal and the fast/slow trick
How a linked list stores data, what it's good and bad at compared to an array, and the two pointer techniques behind most linked-list interview problems.
In short
A linked list is a chain of nodes, each pointing to the next. Inserting or removing at a known node is O(1), but reaching the k-th element is O(k). Interview problems are mostly about rewiring pointers carefully.
Arrays vs linked lists
| Operation | Array | Linked list |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert / delete at the front | O(n) | O(1) |
| Insert / delete after a known node | O(n) | O(1) |
| Memory | Compact, cache friendly | A pointer per node, scattered |
In practice arrays win almost always. Linked lists matter in interviews because they test whether you can manipulate references without losing nodes.
Watch the pointers move
Switch between the two classic algorithms. In reversal the order of the three statements is everything; in fast/slow the speed difference does the work.
1def reverse(head):2 prev, curr = None, head3 while curr:4 nxt = curr.next5 curr.next = prev6 prev, curr = curr, nxt7 return prev
Variables
The toolbox
- Dummy head: put a fake node before the head so inserting or deleting the first node needs no special case.
- Fast and slow pointers: find the middle, detect a cycle (fast catches slow), find the k-th node from the end (move one pointer k steps ahead first).
- Reverse in place: prev / curr / next. Save
nextbefore you overwritecurr.next. - Merge two sorted lists: a dummy head and a tail pointer, taking the smaller front each time.
Key takeaways
- 01Linked lists trade O(1) rewiring for O(n) access.
- 02Save next before changing a pointer; use a dummy head to avoid special cases.
- 03Fast/slow pointers find the middle and detect cycles in O(n) time, O(1) space.
- 04Draw the nodes and arrows; most bugs are visible on paper.
Check your understanding
1 of 3
What's the cost of inserting right after a node you already hold?
Related topics
Two pointers
Put two indices in the array and move them by a rule so that every move rules out many candidates at once. Checking all pairs is O(n²); two pointers does it in one pass, O(n), with no extra memory.
8 min read →Stacks & queues
A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.
7 min read →