Where it runs
1. The problem
A browser's back history, a playlist and a chain of undo steps are built the same way. Each item knows only the one after it: "then this, then this, then this." There are no numbers to jump to. To reach the fifth item, you follow the links from the first.
This is the linked list you built in the two previous lessons. Each item is a node { val, next }: a value and a link to the next node (null in the last one). Now the task: turn the whole chain around. The last node should become the first, and every link should lead the other way.
The simplest way: copy all the values into an array, reverse the array, and build the chain again. That works, but it needs a second copy of all the data. You can turn the links around right where they are: one pass over the nodes and three variables.
This step is part of the paid track
The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.
Create a free accountSee what is includedreverseList(1 → 2 → 3 → 4 → 5)Every arrow points right. prev starts at null, curr at the head.
Recognise it
Say these words and it is this pattern
- reverse a linked list (whole list or between positions)
- reverse in groups of k
- no extra array or O(1) extra space allowed
- swap pairs of nodes
- singly linked list, only .next available
Looks similar, isn't
- Linked list merge & reorder
Merging weaves two lists into one. Reversal rewires a single list in place.
- Fast & slow pointers
That pair finds a midpoint or a cycle by walking. It never changes a link.
- Stack (LIFO)
Pushing every node and popping it also reverses the order. That costs O(n) memory.
- Recursion
The recursive version reads well but uses n stack frames. The loop uses three variables.
n up to 1e6 gives O(n) time and O(1) space. The recursive form instead costs O(n) stack.
On LeetCode
Problems that reverse a linked list, either all of it, one section of it, or every block of k nodes. Save next, turn the pointer back, then move prev and curr forward.
This is the lesson task with the same three pointers.
Walk to the node before left, reverse right minus left plus 1 nodes, then reconnect both ends.
Reversal in blocks of 2, each block joined back to the part already done.
Check that k nodes remain, reverse them, attach the block, and leave a short tail as it is.