https://leetcode.com/problems/reverse-linked-list-ii/
翻转链表第m和第n个之前的元素
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode res = new ListNode(-1);
ListNode pre = new ListNode(-1);
ListNode start = new ListNode(-1);
pre.next = head;
res = pre;
int cnt = 0;
while (head != null) {
if (cnt < m - 1) {
pre = pre.next;
head = head.next;
cnt++;
continue;
}
if (cnt == m - 1) {
start = pre;
pre = pre.next;
head = head.next;
cnt++;
continue;
}
if (cnt > m-1 && cnt < n) {
ListNode tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
cnt++;
continue;
}
if (cnt == n) {
//如果放这里,有一个例子可以作证有问题 input:[3,5],m=1,n=2
// start.next.next = head;
// start.next = pre;
break;
}
}
start.next.next = head;
start.next = pre;
return res.next;
}