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() functionif(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;}
};