Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null)
            return head;
        int index = 1;
        ListNode temp = head, previous = null, start = null, end = null;
        while (temp != null) {
            if (index + 1 == m)
                previous = temp;
            else if (index == m) {
                start = temp;
                ListNode prev = null;
                while (index <= n) {
                    if (index == n)
                        end = temp;
                    ListNode t = temp.next;
                    temp.next = prev;
                    prev = temp;
                    temp = t;
                    index++;
                }
                if (previous != null)
                    previous.next = end;
                else 
                    head = end;
                start.next = temp;
                break;
            }
            temp = temp.next;
            index++;
        }
        return head;
    }
}

Last updated