思想:将各种情况分开讨论,且注意最好统一进行移动操作,这样不容易混淆
时间复杂度O(n),空间复杂度O(1)
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null||m==n)return head;
int counts = 0;
ListNode temp = head,tempHead = null ,rear = null;
if(m==1){
tempHead = new ListNode(-1);
rear = head;
}
while(temp!=null){
counts++;
ListNode next = temp.next;
if(tempHead==null&&counts==m-1){
tempHead = temp;
}
if(counts==m){
tempHead.next = null;
rear = temp;
}
if(counts>=m&&counts<=n){//开始利用头插法进行逆置
temp.next = tempHead.next;
tempHead.next = temp;
}
if(counts==n+1){
rear.next = temp;
return (m==1)?tempHead.next:head;
}
temp = next;
}
return (m==1)?tempHead.next:head;
}
}