Reversing a list
After this: Reverse a list with prev, cur and nxt, one node at a time.
On this page · 8 sections · 4 checks
You can now walk a list, and you can change its pointers in a safe order. This lesson puts the two together to do a job that interviewers often ask for: turning a list around.
The list is 3 → 5 → 7, and we want 7 → 5 → 3. We do not want to make any new nodes. The nodes stay where they are, and only the arrows change direction.
The idea
Picture three people standing in a line, each pointing at the person in front. You walk along the line and ask each person to point backwards instead, at the person behind them.
There is one problem. Once a person has turned around, they no longer show you who comes next. So before you turn anyone, you look ahead and remember who is next.
That is the whole method. We call changing one node's next so that it points backwards a flip. The list needs one flip for each node.
Three variables
We need three variables as we go, and each one holds a pointer.
curis the node we are about to flip. It starts at the head.previs the node behindcur, which has already been flipped. At the start there is no such node, soprevis Nonenull.nxtis the node ahead ofcur. We save it before the flip, because the flip overwrites the only pointer to it.
The code spells it nxt so that it is not confused with the field next. The visualizer labels the same thing next.
Reversing 3 → 5 → 7, step by step
Each round does the same three things: save, flip, advance.
At the start, prev is nothing and cur is on 3.
Round 1, with cur on 3.
- Save:
nxtis 5. - Flip: 3 now points at
prev, which is nothing. - Advance:
prevmoves to 3, andcurmoves to 5.
The flipped part is now 3. The part still to do is 5 → 7.
Round 2, with cur on 5.
- Save:
nxtis 7. - Flip: 5 now points at
prev, which is 3. - Advance:
prevmoves to 5, andcurmoves to 7.
The flipped part is now 5 → 3. The part still to do is 7.
Round 3, with cur on 7.
- Save:
nxtis nothing, because 7 is the last node. - Flip: 7 now points at
prev, which is 5. - Advance:
prevmoves to 7, andcurmoves to nothing.
The flipped part is now 7 → 5 → 3, and nothing is left to do. cur is nothing, so the loop stops. prev is on 7, the last node flipped, and 7 is the new first node. That is why the function returns prev.
Here are the same three rounds in one table.
| Round | Save nxt | Flip cur.next | Advance | List from prev |
|---|---|---|---|---|
| 1 | 5 | 3 points at nothing | prev 3, cur 5 | 3 |
| 2 | 7 | 5 points at 3 | prev 5, cur 7 | 5 → 3 |
| 3 | nothing | 7 points at 5 | prev 7, cur nothing | 7 → 5 → 3 |
The code
def reverse(head): prev = None cur = head while cur is not None: nxt = cur.next # save the rest before the flip cur.next = prev # the flip: point cur backwards prev = cur # advance both pointers one node cur = nxt return prev # the last node flipped is the new headstatic Node reverse(Node head) { Node prev = null; Node cur = head; while (cur != null) { Node nxt = cur.next; // save the rest before the flip cur.next = prev; // the flip: point cur backwards prev = cur; // advance both pointers one node cur = nxt; } return prev; // the last node flipped is the new head}Here is how to read it.
- The two lines before the loop set up the start:
previs Nonenull, andcuris the head. - The loop runs once for each node, until
curis Nonenull. - The highlighted lines are the save and the flip.
- The next two lines are the advance.
prev = curhas to come first. Ifcurmoved first,prevcould not reach the nodecurwas on. - The function returns
prev, the new first node. The old head is now the last node, so the caller must writehead = reverse(head).
head = build([3, 5, 7])head = reverse(head)print(show(head), head.next.value)7 -> 5 -> 3 5
Node head = build(3, 5, 7);head = reverse(head);System.out.println(show(head) + " " + head.next.value);7 -> 5 -> 3 5
What it costs
Three nodes took three flips, and n nodes take n flips. So reversing goes through the list once, which is O(n). It needs only the three variables, however long the list is. Changing the existing data like this, and not building a copy, is called working .
Watch it happen
Go through the first reverse one step at a time, and read the small labels under the nodes. They show where prev, cur and next are. The second reverse has four nodes, so it makes four flips.
- ReverseReverse 3 → 5 → 7. Go one step at a time. After each flip, read where the labels prev, cur and next sit.
- Append 1
- Reverse
Run an operation to begin.
Check yourself
Why does reverse save nxt = cur.nextNode nxt = cur.next before the flip?
What does this print?
head = build([3, 5, 7])head = reverse(head)print(show(head), head.next.value)Node head = build(3, 5, 7);head = reverse(head);System.out.println(show(head) + " " + head.next.value);You are reversing 3 → 5 → 7. Stop after the second flip and the advance that follows it. What do you see if you start at prev and follow next?
Complete reverse. The missing line is the flip. The line above it has already saved the rest of the list in nxt.
def reverse(head): prev = None cur = head while cur is not None: nxt = cur.next # save the rest before the flip ______________________ # ← the flip: point cur backwards prev = cur cur = nxt return prevstatic Node reverse(Node head) { Node prev = null; Node cur = head; while (cur != null) { Node nxt = cur.next; // save the rest before the flip ______________________ // ← the flip: point cur backwards prev = cur; cur = nxt; } return prev;}Connect
- Reverse a list with prev, cur and nxt, doing three things for each node: save, flip, advance.
- Follow where prev and cur sit after each flip, and say why prev is the new head at the end.