linked-list
pointers
Given the head of a singly linked list and two integers left and right (1-indexed, left <= right), reverse the nodes from position left to position right, then return the head of the modified list.
Input / output
- Input:
head: ListNode,left: int,right: int(JSON test fixture forheadis a plain array of node values, e.g.[1, 2, 3, 4, 5]means1 -> 2 -> 3 -> 4 -> 5 -> null) - Output:
ListNode(serialized the same way)
Constraints
- The number of nodes in the list is between 1 and 500.
-500 <= node value <= 5001 <= left <= right <= number of nodes
Follow-up
Can you do it in a single pass through the list, without ever counting the length or making a second traversal?
Examples
Example 1
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example 2 (single node, left==right)
Input: head = [5], left = 1, right = 1
Output: [5]
Example 3 (reverse entire two-node list)
Input: head = [1,2], left = 1, right = 2
Output: [2,1]
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.