To reverse a specific segment of a linked list between positions left and right:
- Use a dummy head to handle cases where the reversal starts at the first node.
- Locate the node immediately preceding the reversal range (
superior). - Reverse the nodes within the range using a standard reversal loop.
- Reconnect the reversed segment: connect the original start of the segment (now the tail) to the node following the range, and connect the
superior node to the new head of the reversed segment.
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode superior = dummyHead;
for(int i = 1; i < left; i++) {
superior = superior.next;
}
ListNode curr = superior.next;
ListNode prev = null;
for(; left <= right; left++) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
superior.next.next = curr;
superior.next = prev;
return dummyHead.next;
}
}