1 → 2 → 3 → null→ 3 → 2 → 1 → nullEach next reference changes direction and the old tail becomes the new head.
Given the head of a singly linked list, reverse its next references and return the new head. Keep every original node; an empty list stays empty.
1 → 2 → 3 → null→ 3 → 2 → 1 → nullEach next reference changes direction and the old tail becomes the new head.
7 → null→ 7 → nullA one-node list has no edge to reverse.
null→ nullThere is no node to process or return.
Read all values into an array, then build a new list in reverse order. This takes O(n) time and O(n) extra space, but does not practice the constant-space pointer rewiring the interview question is designed to test.
Keep previous and current references. Before changing current.next, save it as following. Redirect current.next to previous, move previous to current, and move current to following. When current becomes null, previous is the new head.
Before each iteration, previous heads a correctly reversed prefix of the original list, while current heads the untouched suffix. Saving following preserves access to the suffix; redirecting one edge safely extends the reversed prefix by one node.
Each of n nodes is visited once, so the pointer-rewiring approach uses O(n) time and O(1) extra space. The returned list reuses existing nodes; no new data nodes are needed.
For 1 → 2 → 3, if you set 1.next to null before saving its original next reference, node 2 and the rest become unreachable from your current state. Save following first, then rewire.
Node numbers below identify original objects, even when values repeat. Follow the saved next reference before the arrow turns around.
Current: node #1 (1) · saved next: node #2
Reversed prefix: #1:1 → null
Untouched suffix: #2:2 → #3:3 → #4:4 → null
These choices help you inspect the reasoning. Only the separate code pass records an independent solve.
Write solve(head). A node has val and next, and head may be null. Return the new head after reversing the chain. The local grader compares the returned structure; it does not certify that you used the original node identities or constant memory.
Opening the code studio…
Loading your saved attempts…
For additional practice, see the related LeetCode challenge.