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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode cur1 = dummy;
        ListNode pre1 = null;
        for (int i = 0; i < m; i++) {
            pre1 = cur1;
            cur1 = cur1.next;
        }

        ListNode cur2 = cur1;
        ListNode pre2 = pre1;
        ListNode nxt = null;
        for(int i = m; i <= n; i++) {
            nxt = cur2.next;
            cur2.next = pre2;
            pre2 = cur2;
            cur2 = nxt;
        }

        // connect 1 -> 4
        pre1.next = pre2;
        // connnect 2 -> 5
        cur1.next = cur2;

        return dummy.next;
    }
}
02-11 08:08