题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
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) {
        // write code here
    
        if (head == null || head.next == null || m == n) {
            return head;
        }
        ListNode sourceHead = head;
        ListNode prem = null;
        ListNode behindn = null;
        // {3,5},m=1,n=2
        //prem指向m的前置节点
        //如果m=1则,前置节点指向null
        for (int i = 1; i < m; i++) {
            if (i + 1 == m) {
                prem = head;
                System.out.println("prem:" + prem.val);
            }
            head = head.next;
        }
        Stack<ListNode> stack = new Stack<>();
        //把m-n的元素放入栈
        for (int j = m; j <= n; j++) {
            stack.push(head);
            head = head.next;
        }
        //behindn指向n的后置节点
        behindn = head;
        //System.out.println("behindn:" + behindn.val);
        ListNode node = new ListNode(-1);
        ListNode tempNode = node;
        // stack中节点组装成链表
        while (!stack.isEmpty()) {
            node.next = stack.pop();
            node = node.next;
        }
        //组装成完整的链表
        if (prem != null) {
            prem.next = tempNode.next;
        } 
        //如果m的前置节点是个null,则sourceHead为第一个节点
        else {
            sourceHead = tempNode.next;
        }
        node.next = behindn;
        return sourceHead;
    }
}

