Linked Lists Reversing and rewiring
306. Reverse Linked List II
You are given head, the first node of a singly linked list, and two integers left and right. Reverse the
order of the nodes from position left to position right, and return the head of the list.
Positions start at 1: the head is node 1, the node after it is node 2, and so on. The nodes before position
left and the nodes after position right stay where they are.
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.
Example 1
Input: head = [3, 8, -1, 6, 2, 9, 5], left = 2, right = 5
[3,2,6,-1,8,9,5]Explanation: Nodes 2 to 5 hold 8, -1, 6 and 2. They come back in the order 2, 6, -1, 8. The node holding 3 stays first, and the nodes holding 9 and 5 stay at the end.
Example 2
Input: head = [40, -10, 25], left = 1, right = 2
[-10,40,25]Explanation: The stretch starts at the head, so the head changes. The node holding -10 is the new head, and the node holding 40 comes after it.
Example 3
Input: head = [6, -4, 0, -4], left = 3, right = 4
[6,-4,-4,0]Explanation: The stretch ends at the last node. The last two nodes swap places, so the list now ends with the node holding 0.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 1091 ≤ left ≤ right ≤ number of nodes
Clarifying questions
What you would ask an interviewer before writing any code.