package com.heu.wsq.leetcode.mylinkedlist;
public class ReverseBetween {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head == null || left > right){
return head;
}
ListNode hair = new ListNode(0);
hair.next = head;
ListNode start = null;
ListNode end = null;
ListNode pre = null;
ListNode p = hair;
int n = 0;
while(p != null){
if(n + 1 == left){
pre = p;
start = p.next;
}
if(n == right){
end = p;
break;
}
n++;
p = p.next;
}
ListNode[] arr = reverse(start, end);
pre.next = arr[0];
return hair.next;
}
private ListNode[] reverse(ListNode start, ListNode end){
ListNode prev = end.next;
ListNode curr = start;
while(curr != end){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
curr.next = prev;
return new ListNode[]{end, start};
}
}