Find the start and end node for reversing.
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode temp = dummy;
int index = 1;
while (index < m) {
temp = temp.next;
index++;
}
ListNode prev = temp;
ListNode newHead = temp.next;
while (index <= n) {
temp = temp.next;
index++;
}
ListNode end = temp.next;
prev.next = reverse(newHead, end);
return dummy.next;
}
private ListNode reverse(ListNode head, ListNode end) {
if (head == null || head.next == null) return head;
ListNode prev = new ListNode(-1);
prev.next = head;
ListNode curr = head;
while (curr.next != end) {
ListNode temp = curr.next;
curr.next = temp.next;
temp.next = prev.next;
prev.next = temp;
}
return prev.next;
}
No comments:
Post a Comment