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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if(m == n || head == null ||m > n){
            return head;
        }
        
        ListNode temp = new ListNode(-1);
        
        ListNode currentNode = head;
        //0<m≤n≤size
        int count = 0;
        //区间  before  ..... first .... last ... after
        //first  last 间需要倒转
        ListNode first = null ,last= null;
        ListNode before = null,after = null;
        while(currentNode != null){
            count ++;
            ListNode next = currentNode.next;
            if(count == m - 1){
                before = currentNode;
            }
            if(count == n + 1){
                after = currentNode;
            }
            if(count >= m && count <= n){
                ListNode pre = temp.next;
                
                if(pre == null){
                    //最开始第 m 个位置节点
                    first = currentNode;
                }
                
                
                temp.next = currentNode;
                currentNode.next = pre;
            }
            currentNode =  next;
        }
        if(first != null  && before != null){
            last = temp.next;
            before.next = last;
            first.next = after;
             return head;
        }
        //从第一个数开始
        if(before == null){
           last = temp.next;
            first.next = after;
            return last;
        }
        return head;
    }
}