Linked List · Lesson
Linked lists, explained: dummy nodes, fast and slow pointers and reversal
Learn linked lists: dummy nodes, fast and slow pointers, nth from the end and in-place reversal, with templates in Java, Python, C++ and JavaScript.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What a linked list gives you
A linked list is a chain of nodes. Each node holds a value and a pointer to the next node; the last one points to null. The nodes can live anywhere in memory, so there is no index math: reaching the i-th node means walking i steps, O(n).
The win is the other side. Once you stand at a node, inserting or deleting right after it is O(1): you only change one or two pointers, nothing shifts. Every linked list problem is about changing those pointers in the right order.
Pointer discipline
- Save before you cut. Before you overwrite
curr.next, keep the old value in a variable, or the rest of the list is lost. - Draw it. Three boxes and arrows on paper catch most bugs faster than reading code.
- Check the edges: an empty list, one node, two nodes, and the change happening at the head or the tail.
- Most problems want O(1) extra space. Copying the values into an array works, but interviewers usually ask you to rewire the nodes instead.
How to pick the pattern
- The head might be deleted, swapped or replaced: put a dummy node in front of it.
- The middle, a cycle, or where a cycle starts: fast and slow pointers.
- The n-th node from the end in one pass: two pointers with a gap of n.
- Reverse the list, a part of it, or k nodes at a time: prev, curr and next pointers.
- Split, interleave, copy or sort: build new lists behind tail pointers and join them at the end.
What it costs
| Operation | Time | Space |
|---|---|---|
| Read the i-th node | O(n) | O(1) |
| Insert or delete after a node you hold | O(1) | O(1) |
| Insert at the head | O(1) | O(1) |
| Search for a value | O(n) | O(1) |
| Reverse in place | O(n) | O(1) |
| Find the middle or detect a cycle | O(n) | O(1) |
| Sort (merge sort) | O(n log n) | O(log n) recursion |
Built into your language
// interview problems give you this node
class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
// the built-in doubly linked list, also a deque
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(1); list.addLast(2); // O(1) at both ends
list.peekFirst(); list.pollLast(); // 1, then removes 2
list.get(5); // O(n): it walks the list class ListNode: # the node interview problems give you
def __init__(self, val=0, next=None):
self.val, self.next = val, next
from collections import deque # Python has no linked list type; deque covers the ends
dq = deque([1, 2])
dq.appendleft(0); dq.append(3) # O(1) at both ends
dq.popleft(); dq.pop() # 0, 3 struct ListNode { int val; ListNode* next; ListNode(int v) : val(v), next(nullptr) {} };
list<int> l = {1, 2, 3}; // doubly linked list
l.push_front(0); l.push_back(4); // O(1) at both ends
auto it = next(l.begin(), 2); // walking to a position is O(n)
l.insert(it, 9); l.erase(it); // O(1) once you hold the iterator
l.reverse(); l.sort(); // member functions, no std::sort // JavaScript has no built-in linked list: you write the node yourself
class ListNode {
constructor(val = 0, next = null) { this.val = val; this.next = next; }
}
const head = new ListNode(1, new ListNode(2, new ListNode(3)));
for (let p = head; p; p = p.next) console.log(p.val); // 1 2 3 Mistakes everyone makes
- Overwriting
curr.nextbefore saving it: the rest of the list is gone. - Returning
headafter the head was deleted or moved: returndummy.next. - Checking
fast.nextbeforefast: testfast != null && fast.next != null, in that order. - Forgetting to set the new tail's
nexttonullafter splitting or rearranging, which leaves a cycle. - Comparing nodes by value when the problem means the same node (intersection, cycles): compare the references.
The 5 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Dummy node: no special case for the head Put a fake node in front of the head. Now every real node, the head included, has a node before it, so deleting, swapping or building a list needs no special case. Return
dummy.nextat the end. 3 variations · 8 problems - 2 Fast and slow pointers: middles and cycles Move one pointer one step and another two steps. When the fast one reaches the end, the slow one is in the middle. If there is a cycle, the fast one laps the slow one and they meet, all in O(1) space. 3 variations · 6 problems
- 3 Front and back pointers: the n-th node from the end Move a front pointer n steps ahead, then move both pointers together. When the front one hits the end, the back one is exactly n nodes from the end, in a single pass. 1 variation · 1 problem
- 4 In-place reversal: prev, curr and next Walk the list with three pointers: save
next, pointcurrback atprev, then step both forward. The same loop reverses the whole list, one part of it, or k nodes at a time, in O(1) space. 3 variations · 4 problems - 5 More linked list tricks: split, copy, intersect and sort A few problems need their own small idea: build separate lists and join them, copy a node's value instead of deleting it, let two pointers swap lists to meet, or merge sort with a middle split. 6 variations · 8 problems