import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // 定义hair节点,避免空指针判断
        ListNode hair = new ListNode(0);
        hair.next = head;
        ListNode pre = hair;
        ListNode tempPre = pre;
        ListNode temp = head;
        for (int i = 1; i <= n; i++) { //必须遍历到最后一个节点,否则m=n的时候pre节点不对
            if (i == m) {
                pre = tempPre;
            }
            tempPre = temp;
            temp = temp.next;
        }
        ListNode next = temp;

        // 正常链表逆序
        ListNode swapHead = pre.next;
        ListNode swapTail = tempPre;
        ListNode swapPre = null;
        ListNode swapTemp = swapHead;
        while (swapTemp != next) {
            ListNode swapNext = swapTemp.next;
            swapTemp.next = swapPre;
            swapPre = swapTemp;
            swapTemp = swapNext;
        }

        // 三段数组拼接起来
        pre.next = swapPre;
        swapHead.next = next;
        return hair.next;
    }
}