翻转链表(二)

题目:
描述
翻转链表中第 m 个节点到第 n 个节点的部分。

m,n 满足1 ≤ m ≤ n ≤ 链表长度

样例
样例 1:

输入:
链表 = 1->2->3->4->5->NULL
m = 2
n = 4

输出:
1->4->3->2->5->NULL
解释:

翻转链表[2,4]位置。

样例 2:

输入:
链表 = 1->2->3->4->null
m = 2
n = 3

输出:
1->3->2->4->NULL
解释:
翻转链表[2,3]位置。

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: ListNode head is the head of the linked list 
     * @param m: An integer
     * @param n: An integer
     * @return: The head of the reversed ListNode
     */
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // write your code here
        if(head == null) {
            return null;
        }

        if(m == n) {
            return head;
        }

        ListNode root = new ListNode(0);
        root.next = head;
        ListNode pr = root, cur = head;
        for(int i = 1; i < m; i++) {
            pr = cur;
            cur = cur.next;
        }

        ListNode tail = root;
        for(int i = 0; i < n; i++) {
            tail = tail.next;
        }

        ListNode target = tail.next;

        pr.next = reverse(cur, target);

        return root.next;
    }

    private ListNode reverse(ListNode start, ListNode end) {
        ListNode pr = start, cur = start.next, node = start;
        while(cur != end) {
            ListNode tmp = cur.next;
            cur.next = pr;
            pr = cur;
            cur = tmp;
        }

        node.next = cur;
        return pr;
    }
}