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
.
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(k==0 || head==null || head.next==null ){ //不做调整
return head;
}else{
ListNode p=head;
int count = 0 ;
while(p!=null){ //记录链表的总个数
count++;
p=p.next;
}
if(k%count==0){ //k正好指向头结点
return head;
}else{
p=head; //p重新指向head
if(k>count)
{k=k%count;} //从左数k的顺序
int err=count-k;
int i=1;
while(i<err){ //循环结束后,p正好指向右数第k个数的前驱节点
p=p.next;
i++;
}
ListNode headb=p.next,r=p.next;
p.next=null;
while(r.next!=null){
r=r.next;
}
r.next=head;
return headb;
}
}
}
}