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
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getSize(ListNode *head){
ListNode *p=head;
int counter=0;
while(p){
p=p->next;
counter++;
}
return counter;
}
ListNode *rotateRight(ListNode *head, int k) {
if(k<=0||head==NULL){
return head;
}
k%=getSize(head);//注意这里,k的大小可能超过链表长度
if(k==0){
return head;
}
ListNode *p=head, *q=head, *r;
int counter=0;
while(q&&counter<k){//循环直到q指向正数第k+1个结点
q=q->next;
counter++;
}
while(q->next){//循环直到q指向最后一个结点时,p正好指向倒数第k+1个结点
p=p->next;
q=q->next;
}
q=p->next;
p->next=NULL;
p=q;//p、q分别指向需要提前的结点的首、尾结点
while(q->next){
q=q->next;
}
q->next=head;
head=p;
return head;
}
};