思路:利用栈的先进后出原理解题,首先找到要反转区域的前一点pre,防止一开始就要反转,故需要创建一个表头,利用for循环将要反转的区域放入栈中,再利用while循环将栈中元素拼接到pre后面,再接上栈后元素;
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类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
Stack<ListNode> stack = new Stack<>();
//价格表头,以便找到反转区域前一点
ListNode res = new ListNode(-1);
res.next = head;
ListNode pre = res;
ListNode cur = head;
//找到m处,pre为m前一点
for(int i = 1; i < m; i++){
pre = cur;
cur = cur.next;
}
//将要反转的区域放进栈中
for(int i = m; i <= n; i++){
stack.push(cur);
cur = cur.next;
}
//将栈中元素弹出,并接到pre后面
while(!stack.isEmpty()){
pre.next = stack.pop();
pre = pre.next;
}
//将区域后面剩余元素连接上
pre.next = cur;
//去掉表头
return res.next;
}
}