Reverse Linked List II
Problem
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.
Examples
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.
Constraints
- •
The number of nodes in the list is n - •
1 <= n <= 500 - •
-500 <= Node.val <= 500 - •
1 <= left <= right <= n
Hints
Hint 1
This 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.
Hint 2
Use a dummy node before head so 'left == 1' (reversing from the very start) isn't a special case needing separate logic.
Hint 3
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.
Solutions
public ListNode reverseBetweenBruteForce(ListNode head, int left, int right) {
List<Integer> values = new ArrayList<>();
ListNode curr = head;
while (curr != null) { values.add(curr.val); curr = curr.next; }
Collections.reverse(values.subList(left - 1, right)); // reverse just the target sub-range in place
curr = head;
for (int v : values) { curr.val = v; curr = curr.next; } // write values back into the existing nodes
return head;
}Time: O(n) · Space: O(n)