Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right (1-indexed), and return the reversed list.
Example 1
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Explanation: Nodes at positions 2 through 4 (values 2,3,4) are reversed in place; positions 1 and 5 stay put.
Example 2
Input: head = [5], left = 1, right = 1
Output: [5]
Explanation: Reversing a single node is a no-op.
The number of nodes in the list is n1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= nThis is the same three-pointer (prev/curr/next) reversal as the full-list version — the difference is entirely about where you start and stop, and reconnecting the reversed sub-range back to the untouched parts.
Use a dummy node before head so 'left == 1' (reversing from the very start) isn't a special case needing separate logic.
Walk to the node just before position 'left' first — everything before that node never moves, and you need a stable reference to reconnect to it afterward.
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0, head); // handles left == 1 without a special case
ListNode beforeLeft = dummy;
for (int i = 0; i < left - 1; i++) beforeLeft = beforeLeft.next; // walk to just before 'left'
ListNode curr = beforeLeft.next; // this will become the TAIL of the reversed section
ListNode prev = null;
for (int i = 0; i < right - left + 1; i++) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// Reconnect: beforeLeft -> (reversed section, head = prev) ... (reversed section, tail) -> curr (first node after the range)
beforeLeft.next.next = curr; // the original 'left' node is now the tail of the reversed section
beforeLeft.next = prev; // prev is the new head of the reversed section
return dummy.next;
}Time: O(n) · Space: O(1)