Reverse List

Reverse List

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.

Examples

1 → 2 → 3   // → 3 → 2 → 1
7           // → 7
(empty)     // → (empty)

Walkthrough

Thinking it through

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.

Why you can't just flip pointers as you walk forward

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.

Building the approach with three pointers

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:

  1. A pointer to the reversed portion so far ("previous") — starts as nothing.
  2. A pointer to the node you're processing now ("current") — starts at the original head.
  3. A temporary pointer to save current's original next node before you overwrite anything.

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.

Why "previous" is the answer at 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.

Edge cases resolve naturally

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.

Why this is efficient

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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.