Reverse Linked List II
Given the headleftrightleft <= rightleftright
Example 1
Input: head = [1, 2, 3, 4, 5], left = 2, right = 4
Output: [1, 4, 3, 2, 5]
Explanation: The sublist from position 2 to 4 ([2, 3, 4]) is reversed to [4, 3, 2].
Output: [1, 4, 3, 2, 5]
Explanation: The sublist from position 2 to 4 ([2, 3, 4]) is reversed to [4, 3, 2].
Example 2
Input: head = [5], left = 1, right = 1
Output: [5]
Output: [5]
Solution Approach
We use a single-pass approach. A dummy node is prepended to handle edge cases where reversal starts from the head.
We advance to the node just before position leftprev
- Create a
node that points todummy . Sethead .prev = dummy - Advance
exactlyprev steps so it sits just before the sublist start.left - 1 - Let
(the first node of the sublist to reverse).curr = prev.next -
Repeat
times: take the node afterright - left , remove it from its position, and insert it immediately aftercurr . This effectively reverses the sublist one node at a time.prev - Return
as the new head.dummy.next
Java
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class ReverseLinkedListII {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
// Move prev to (left-1)-th node
for (int i = 0; i < left - 1; i++) {
prev = prev.next;
}
ListNode curr = prev.next;
// Perform (right - left) insertions
for (int i = 0; i < right - left; i++) {
ListNode next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummy.next;
}
}
Complexity Analysis:
Time complexity: O(n) where n is the length of the linked list. We traverse the list at most once.
Space complexity: O(1) since we reverse in-place using only a constant number of pointers.