Problem
Reverse the nodes from position left through position right in a singly linked list, leaving the rest in its original order. Positions are one-based and inclusive. Return the resulting head using the supplied ListNode type with val and next fields.
ListNode* reverseBetween(ListNode* head, int left, int right);
Examples
Input: head = [8,1,6,3,9], left = 2, right = 5
Output list: [8,9,3,6,1]
Input: head = [4,7,2], left = 1, right = 2
Output list: [7,4,2]
Brackets show the list's values; both the input and result remain node pointers.
Constraints
-
The list has
n
nodes, with
1 <= n <= 500
.
-
Node values are between -500 and 500, inclusive.
-
1 <= left <= right <= n
.
Source follow-up
Can the reversal be done in one pass?