Example 1
- Input
- head = [1,2,3,4,5]
- Output
- [5,4,3,2,1]
Reverse all four original links and terminate node 1 with null. Return the original node 5, so traversing from the returned head visits the original nodes in reverse order.
Given the head of a singly linked list, flip every next pointer so the list runs in the opposite order, and return the new head.
Given the head of an acyclic singly linked list, reverse the direction of every next link and return the new head. An empty list returns null.
Reuse every original node and preserve its value. The original tail becomes the new head, the original head becomes the null-terminated tail, and the caller must use the returned head to traverse the complete result.
Reverse all four original links and terminate node 1 with null. Return the original node 5, so traversing from the returned head visits the original nodes in reverse order.
Point node 2 to node 1 and clear node 1 next. Returning the old head would expose only node 1 rather than both nodes.
There is no node or link to change. Both approaches return null immediately without allocating an output node.
The sole node is already the head and null-terminated tail. The returned reference is the same object.
The original last node comes first even though several values are equal. Correct reversal changes node order and links while preserving each node value.
A node cannot point backward until we remember the node before it. For Example 1, save the link from 1 to 2, point 1 at null, then save the link from 2 to 3 and point 2 at 1. This grows a reversed prefix while keeping the untouched suffix reachable. Recursion reaches the old tail first and performs the same link repair while calls return; iteration stores the needed references directly and avoids a call stack.
Reveal Recursive Reversal: intuition, complexity, and code
prev pointer as you walk forward.curr.next before overwriting it, or the rest of the list becomes unreachable.curr.next before saving its successor loses access to the untouched suffix.List rewiring comes down to saving the next link before overwriting it; that one habit prevents almost every lost-node bug.