The input is head, the first node of a linked list. Each node holds a number, val, and next, the node after it. The last node's next is null (None in Python). Reverse the list, and return the head of the reversed list.
Examples
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = []
Output: []
Linked lists — a node holds a value and a next reference, and rearranging a list means moving references, never values. Dummy heads: a node in front of the list so the first element stops being a special case. Two pointers on a list — one ahead of the other, or one moving twice as fast.
How to think about it
1. Three Pointers, One Pass Optimal
Intuition
Reversing a list is repointing each node at the one behind it. The only difficulty is that following next AFTER changing it loses the rest of the list — so hold the next node before you overwrite anything. When the walk falls off the end, the node you were carrying as "previous" is the new head, and the empty list needs no special case at all.
Algorithm
1. Start with previous as null and current at the head. 2. Save current.next before touching it. 3. Point current.next at previous. 4. Advance previous to current and current to the saved next. 5. Return previous.
Time & Space
Time O(n). Space O(1). The recursive version is O(n) stack, which is worth naming as the tradeoff.
2. Recursion: Reverse the Rest First
Intuition
A list of no nodes, or of one, is its own reverse. A longer list is its head and then the rest: reverse the rest first, and the head of that reversed rest is the answer. The node that was head.next is now the last node of the reversed rest, so pointing its next back at head puts head on the end, and setting head.next to null makes head the new last node.
Algorithm
1. If head is null, or head.next is null, return head: a list of no nodes or one is already reversed. 2. Reverse the rest, from head.next, and keep the head it returns: it is the answer. 3. head.next is now the last node of the reversed rest: point its next back at head. 4. Point head.next at null, so head ends the list. 5. Return the head the call returned.
Time & Space
Time O(n). Space O(n): a call waits on the stack for every node. In Python that stack ends at about 1,000 calls, so a list of about 1,000 nodes or more stops with RecursionError, where the constraints allow 5,000.