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) {
// write code here
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode pre = newHead;
for (int i = 0; i < m - 1; i++, n--) {
pre = pre.next;
}
ListNode cur = pre.next;//找到需要断开的结点头
pre.next = null;
ListNode rHead = cur;
for (int i = 0; i < n - 1; i++) {
rHead = rHead.next;
}
ListNode tail = rHead.next;//找到需要断开的结点尾
rHead.next = null;
//将中间断开的链表进行反转
ListNode newPre = null;
ListNode rTail = cur;
while (cur != null) {
ListNode temp = cur.next;
cur.next = newPre;
newPre = cur;
cur = temp;
}
//反转之后,再链接到一起
pre.next = newPre;
rTail.next = tail;
return newHead.next;
}
}