Reverse a Sublist of a Linked List
Implement reverseSublist
Given the head of a singly linked list and two 1-indexed positions
left and right (with left ≤ right), reverse only the nodes from position left to position right, then return the head of the modified list. Nodes outside that window keep their original order.
The single-pass solution leans on a trailing prev pointerTrailing Prev PointerKeep a pointer one step behind the section being modified. Because reversing a run of nodes only ever changes .next pointers — never values — anchoring prev right before the window means every node pulled out of the window can be re-inserted immediately after prev with a fixed, three-line relink, with no lookahead and no extra memory.: once prev is parked right before the window, the window's own first node (curr) never moves — it's exactly where it needs to end up as the window's last node — and each subsequent node just gets unhooked and re-inserted right after prev, one at a time, until the whole window is reversed.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example 2:
Input: head = [5], left = 1, right = 1
Output: [5]
Example 3:
Input: head = [3,5], left = 1, right = 2
Output: [5,3]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 500 - ●
-500 ≤ node value ≤ 500 - ●
1 ≤ left ≤ right ≤ number of nodes in head
head =
[1, 2, 3, 4, 5]
left =
2
right =
4