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.
巨没劲的一道题,当k>length 时,我以为origin list 不动就行,结果好些case过不了,看了别人的代码才知道要 k%= length 真心想不通为什么,也懒得弄这种恶心的东西。面试遇到这种题目直接问面试官这种奇葩情况怎么处理就行。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || k == 0) return head;
ListNode *p, *q;
p = head;q= p;
while(q &&--k){
q = q->next;
}
if(k >0 || NULL == q) return head;
ListNode *pre = NULL;
while(q->next){
pre = p;
p = p->next;
q = q->next;
}
q ->next = head;
head = p;
pre ->next = NULL;
return head;
}
};