# What to do when k is greater than size of list ?

• i am not getting that what i should do when K is greater than size of the list.

Given `[0,1,2]`, rotate 1 steps to the right -> `[2,0,1]`.

Given `[0,1,2]`, rotate 2 steps to the right -> `[1,2,0]`.

Given `[0,1,2]`, rotate 3 steps to the right -> `[0,1,2]`.

Given `[0,1,2]`, rotate 4 steps to the right -> `[2,0,1]`.

So, no matter how big K, the number of steps is, the result is always the same as rotating `K % n` steps to the right.

• What does it mean by "rotate to the right" ? I guess it's more like to say "rotate the last node from the left"

• Thanks 1337. This is clear. You should use this as the "problem statement".

• I also get stuck in such case, and finally I got it over. In such case , k = k % size;

• This is my code, Given two pointers, one is faster than the other by k steps ,when k>n I just reset from head.

`````` ListNode *rotateRight(ListNode *head, int k) {
return NULL;
int cnt=0;
while(cnt<k)
{
fast=fast->next;
cnt++;
}
while(fast->next){
fast=fast->next;
slow=slow->next;
}
slow->next=NULL;
}
``````

• if k is very big,your first while may cost much time,why not first find the lenth of the list,define it len,and then the we only need rotate k % len;

• when k is larger than length, k can be replaced by k % length. Or your first while loop will cost a really long time when k is really big.

• {
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int i=0;
while(i!=k&&p!=NULL){
p=p->next;
i++;
}
if(p!=NULL){
while(p->next!=NULL){
p=p->next;
q=q->next;
}
q->next=NULL;

``````    }
else{
k%=i;
}

}
``````

}; // if k is larger than length, k%=i return return rotateRight(head,k);
}

• @rforritz I think if k > list's size, what we should do is rotate the list with `k % lists' size` steps.

• @dingou666 Time Limit Exceeded

• This post is deleted!

• Thanks for your explanation !

• @introom rotate could be better explained as "shift to right".

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.