Reverse a singly linked list and return the new head.
reverseList(head)
Do it by rewiring the existing nodes' Next pointers — no new nodes needed.
Input format: space-separated node values. Output the reversed list, space-separated.
1 → 2 → 3 // → 3 → 2 → 1
7 // → 7
(empty) // → (empty)
Reversing a linked list means every node's next pointer needs to end up pointing at the node that used to come before it, not after. This is different from the traversal problems so far — you're not just reading values, you're rewriting the list's structure in place.
The trap: if you flip a node's next pointer to point backward while standing on it, you immediately lose your only way to reach the rest of the list. So before touching a node's next, you must already have saved a reference to whatever came after it. That's the whole insight: remember "where am I going next" before you destroy the pointer that would have told you.
Think of the list as split into two parts as you walk: a "done" part behind you, already reversed, and an "untouched" part ahead, still pointing the original direction. Three pieces of state manage that boundary:
At each step: save current's next node, rewire current's next to point backward at previous, then slide both previous and current one step forward. Repeat until current runs off the end.
When current becomes the end-of-list marker, every node has been folded into the reversed portion. At that point, "previous" sits on the last node processed — the one that used to be the tail, and now, flipped, is the new head. No extra step needed to find it.
An empty list: current starts as the end marker immediately, the loop never runs, and previous (still nothing) is correctly the new head. A single-node list: the loop runs once, pointing that node's next at nothing — exactly correct, since a one-element list is its own reversal.
Every node is visited and rewired exactly once — linear time. Since you're reusing existing nodes instead of building new ones, only the three pointers cost extra memory, regardless of list length.
def reverse_list(head):
prev = None
curr = head
while curr is not None:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.