2. Linked Lists (Reversal)
Nodes that each hold a value and a pointer to the next node. Inserting next to a node you already hold is O(1), but finding the i-th node is O(n). Reversal with three pointers is the classic warm-up.
How it works
A singly linked list is a chain of nodes, each storing val and next. There is no index arithmetic, so reaching the i-th node means walking i steps. In exchange, inserting or removing a node after one you already hold is just a pointer change.
To reverse a list in place, walk it once with three pointers: prev (the head of the part already reversed), cur (the node being processed) and nxt (saved so we do not lose the rest of the list). Each step flips one arrow.
Diagram
flowchart LR
subgraph before["Before"]
a1["1"] --> a2["2"] --> a3["3"] --> a4["4"] --> a5["None"]
end
subgraph after["After reverse"]
b4["4"] --> b3["3"] --> b2["2"] --> b1["1"] --> b5["None"]
end
Step-by-step trace
Input: Reverse the list 1 -> 2 -> 3 -> 4.
| Iteration | cur | Reversed part (from prev) | Remaining (from cur) |
|---|---|---|---|
| start | 1 | [] | [1, 2, 3, 4] |
| 1 | 2 | [1] | [2, 3, 4] |
| 2 | 3 | [2, 1] | [3, 4] |
| 3 | 4 | [3, 2, 1] | [4] |
| 4 | None | [4, 3, 2, 1] | [] |
Result: New head is 4; the list reads [4, 3, 2, 1].
Complexity
| Operation | Time | Space |
|---|---|---|
| Access i-th node | O(n) | O(1) |
| Insert / delete after a known node | O(1) | O(1) |
| Search | O(n) | O(1) |
| Reverse (iterative) | O(n) | O(1) |
Python reference implementation
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
cur = head
while cur:
nxt = cur.next # remember the rest of the list
cur.next = prev # flip the pointer
prev = cur # grow the reversed part
cur = nxt # move on
return prev
Common mistakes and tips
- Save
cur.nextbefore overwriting it, or the rest of the list is lost. - A dummy head node removes special cases when the head itself may change.
- Fast and slow pointers find the middle or detect a cycle in one pass.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Arrays and Dynamic Arrays | Next: Stacks (Balanced Brackets) |