原題如下:
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
.
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head == NULL || k == 0)
return head;
int n = 1;
ListNode * p = head, *q = head, *tail = head;
while(tail->next != NULL){
n++;
tail = tail->next;
}
k = k % n;
if(k == 0)
return head;
for(int i = 1; i < n - k; i++){
p = p->next;
}
q = p->next;
p->next = NULL;
tail->next = head;
return q;
}
};