# leetcode #61 in cpp

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.

Solution:

If k < length of the node, then we use two pointers to find the new head in the list as what we do in #19, and then we delete the link between the new head and its parent, and add link from the tail to the original head.

1->2->3->4, say 3 is the new head

1->2->null 3->4----

|______________|

If k >= length of the node. we rotate k%length. It is simply like rotating a circle.

Code:

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {

int len = 0;

while(cur){//calculate how long the linked list is
len++;
cur = cur->next;
}

k %=len;

len =0;
while(len<k && cur->next){//separate cur k distance from prev
cur = cur->next;
len++;
}
while(cur->next){//move cur to tail. prev->next is the beginning of the section we are to rotate
cur = cur->next;
prev = prev->next;
}
prev->next = NULL;//put prev as tail

};