Linked Lists Reversing and rewiring
297. Reverse Linked List
You are given head, the first node of a singly linked list. Reverse the order of the nodes, so that the last
node comes first and the first node comes last, and return the head of the reversed list.
A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The
output shows the node you return the same way, as the list from that node on, and shows null as [].
Example 1
Input: head = [4, 7, 1, 9, 2]
[2,9,1,7,4]Explanation: The list 4 → 7 → 1 → 9 → 2 becomes 2 → 9 → 1 → 7 → 4. The node holding 2 was last and is now the head, and the node holding 4 was the head and now ends the list.
Example 2
Input: head = [10, -20]
[-20,10]Explanation: The two nodes swap places. The node holding -20 now points to the node holding 10, which points to null.
Example 3
Input: head = []
[]Explanation: An empty list reversed is still empty, so the answer is null.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.