Reverse a singly linked list in place without losing nodes
Question
A courier's route is a singly linked list of stops: A → B → C → D. Each Node has a stop name and a next link. The courier wants to drive the route backwards.
Write reverse(head). It must reverse the list in place and return the new head, so the route becomes D → C → B → A. Don't create new nodes or copy the stops into a Python list. Use O(1) extra memory. It must also work for an empty route (None) and a route with one stop.
class Node: def __init__(self, stop, next_node=None): self.stop = stop self.next = next_node def reverse(head): ...
Show hints (3)
- "TURN THE ARROWS"
Walk the list once. At each node, turn its
nextarrow around so it points to the node before it. - "DON'T LOSE THE REST"
When you change
current.next, the node forgets where the rest of the list is. Save that link in a variable first. - "THREE NAMES"
Keep
prev,currentandfollowing. Start withprev = Noneandcurrent = head. WhencurrentbecomesNone,previs the new head.
Show checked explanation
Walk the list with three references: prev, current and following. At each node, first save following = current.next, then point current.next back at prev, then move both one step forward. When current is None, return prev. It is O(n) time and O(1) extra memory, and it handles an empty list without a special case.
class Node: def __init__(self, stop, next_node=None): self.stop = stop self.next = next_node def reverse(head): prev, current = None, head while current: following = current.next # save the rest before cutting the link current.next = prev prev, current = current, following return prev route = reverse(Node("A", Node("B", Node("C", Node("D"))))) while route: print(route.stop, end=" ") route = route.next print("|", reverse(None), reverse(Node("X")).stop)
D C B A | None X
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
The loop turns one arrow around per step. prev is the part that is already reversed. current is the next node to fix. following keeps the rest of the route reachable.
| step | following | current.next becomes | reversed part | current after |
|---|---|---|---|---|
| 1 | B | None | A | B |
| 2 | C | A | B → A | C |
| 3 | D | B | C → B → A | D |
| 4 | None | C | D → C → B → A | None |
When current is None, every arrow is turned, and prev points to D, the new head.
What breaks first is the order of the lines. The moment you write current.next = prev, the node loses its only link to the rest of the list. If you haven't saved that link in following, B, C and D are gone. The loop then ends after one step and returns just A.
The empty route needs no special case: the loop never runs, and prev is still None. With one stop, the loop runs once and returns that stop, with its next set to None.
Each node is visited once, so the time is O(n). The function uses three names whatever the length of the route, so the extra memory is O(1).
"In place" also means old names still point to the same nodes. If start held A before the call, start is now the tail: start.next is None. Always use the returned head.
Common mistakes
- Setting
current.next = prevbefore savingcurrent.next. The rest of the list becomes unreachable, and the function returns only A. - Returning
headinstead ofprev. The old head is now the tail, so the caller sees a route with one stop: A. - Starting with
prev = headandcurrent = head.next. A'snextstill points to B, so B → A → B forms a cycle, and printing the route never ends.
Follow-up questions
- "Can you write it recursively?" Yes: reverse the rest of the list, then make the next node point back to the current one. It is shorter, but it uses one stack frame per node. CPython's default recursion limit is 1000, so a route of 5,000 stops raises
RecursionError. The loop has no such limit. - "Reverse only stops 2 to 4 of A → B → C → D → E." Walk to A, the node before stop 2. Run the same loop for exactly three nodes: B, C, D. Then reconnect both ends: A points to D, and B points to E. The result is A → D → C → B → E. A dummy node before the head handles a reversal that starts at stop 1.
What a strong answer covers
Names the three references and saves next before changing it. Returns the new head, and tests an empty list, one node and the old head's next. States O(n) time and O(1) memory, and knows the recursive version can hit the recursion limit.
Open in interactive practice deck →