import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     * pre 1  ; leftnode = 2 ; rightNode 5
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;



        // 走m-1步 到达了leftNode前一个节点
        for(int i = 0 ; i < m-1 ; ++i){
            pre = pre.next;
        }

        ListNode leftNode = pre.next;
        ListNode rightNode = pre;


        for(int i = 0 ; i < n-m+1;i++){
            rightNode = rightNode.next;
        }
        ListNode b = rightNode.next;

        pre.next = ReverseList(leftNode,b);

        return dummy.next;

    }

//     反转[head,b) 返回
    public ListNode ReverseList(ListNode head,ListNode b) {

        if(head == null || head.next == null){
            return head;
        }
        ListNode pre = b,cur = head,nxt = head;  // pre = b可以使得反转后的2 连接到 b:5
        while(cur != b){
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }

        return pre;

    }
}