61. rotate list

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)
return head;
ListNode* tail=head;
int size=1;
//get the size of the ListNode
while(tail->next)
{
tail=tail->next;
++size;
}
tail->next=head;//circle the ListNode
k%=size;//in order to avoid the repeated conduction
//get the position to break the circle
for(int i=0;i<size-k;++i)
{
tail=tail->next;
}
ListNode* ans=tail->next;
//break the circle
tail->next=NULL;
return ans;
}
};