描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1to 2 to 3 to 4 to 5 to NULL1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1to 4to 3to 2to 5to NULL1→4→3→2→5→NULL.
数据范围: 链表长度 0 < size le 10000
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)
import java.util.*;
public class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
//first和last分别确定m和n的位置,
//prefirst用于确定节点m的前一个节点,end用于确定节点n的后一个节点
//p,q,r用于区间m和n中的节点反转
ListNode p,first,last,prefirst;
ListNode q,r,end;
p=head;
first=head;
prefirst=head;
last=head;
end=head;
if(head==null) return null;
if(m==n) return head;
int number1=1;
int number2=1;
while(p!=null){
if(number1==(m-1)){
prefirst=p;
first=p.next;
}
if(number2==n){
last=p;
end=p.next;
break;
}
p=p.next;
number1++;
number2++;
}
p=first;
q=p.next;
p.next=end;
r=q;
while(r!=end){
r=q.next;
q.next=p;
p=q;
q=r;
}
if(m!=1){
prefirst.next=last;
}else{
head=p;
}
return head;
}
}



