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) return head;
List<ListNode> nodeList = new ArrayList<>();
nodeList.add(head);
ListNode target1 = head;
while (true) {
ListNode next = target1.next;
if (next == null) break;
nodeList.add(next);
target1 = next;
}
m = m - 1;
n = n - 1;
if (m == n && m <= nodeList.size()) {
return head;
}
if (m >= 0 && n < nodeList.size() && m < n) {
for (int i = n; i > m; i--) {
ListNode nextTarget = nodeList.get(i);
if (i > 0) {
ListNode nextTarget1 = nodeList.get(i - 1);
nextTarget1.next = null;
nextTarget.next = nextTarget1;
}
}
ListNode body = nodeList.get(n);
ListNode mBody = nodeList.get(m);
if (m > 0) {
ListNode start = nodeList.get(m - 1);
start.next = body;
if (n < nodeList.size() - 1) {
ListNode end = nodeList.get(n + 1);
mBody.next = end;
}
return nodeList.get(0);
} else {
if (n < nodeList.size() - 1) {
ListNode end = nodeList.get(n + 1);
mBody.next = end;
}
return nodeList.get(n);
}
}
return null;
}
}