leetcode

Reverse Linked List II

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

For example:

Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:

Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

The idea is to find the previous node to m and next node to n and then use reverse in between (m-1, n+1).

public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head==null||head.next==null) {
            return head;
        }

        int i=1;
        ListNode current = head;
        ListNode previous = new ListNode(0);
        previous.next = current;

        while (i<=n) {
            if (i<m) {
                previous = current;
            }
            current = current.next;
            i = i+1;
        }

        //exclusive previous and current
        reverseInBetween(previous, current);

        return m>1 ? head : previous.next;
    }

    private void reverseInBetween(ListNode previous, ListNode next) {
        ListNode last = previous.next;
        ListNode current = last.next;

        while (current!=next) {
            last.next = current.next;
            current.next = previous.next;
            previous.next = current;
            current = last.next;
        }
    }