Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
使用two pointer的方法 slow和fast始终间隔k,有个条件这里是当fast遍历到list尾的时候,需要将fast重新置为head
然后slow和fast同时向后走,当fast.next==null的时候,slow的位置就是rotate完list的结尾
slow.next=null
fast.next=head
然后返回原来slow.next就可以了
遍历一次 时间O(n), 空间O(1)
public ListNode rotateRight(ListNode head, int n) {
if(head==null){
return null;
}
if(n<=0){
return head;
}
ListNode fast=head;
ListNode slow=head;
int count=n;
while(count>0){
if(fast.next==null){
fast=head;
}
else fast=fast.next;
count--;
}
if(fast.equals(head)){
return head;
}
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
/*
Rotate Operation
*/
ListNode newHead=slow.next;
fast.next=head;
slow.next=null;
return newHead;
}