Rotate List
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
.
注意rotate回头的情况:
{1,2,3}, 5wrong:{1,2,3}right:{2,3,1}
突然想到,在白板上写程序,因为space limited,最好不要用无谓的{,},而且尽量在同一行使得代码在保证可读性的情况下尽量短!!!
所以第二遍过的时候要注意怎么样代码更加的简洁
/** * 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 (!k) return head; ListNode dummynode(0), *h = &dummynode,*p = head, *e = p; h->next = head; //rotate回来的情况,先得到总长度 int length = 0; for(e = p;e;e = e->next){ length ++; } //如果是满足mod的关系,可以直接返回,%的分母不能为0 if (length && k%length == 0){ return head; } int n = 0; for(e = p;e;e = e->next){ if (n++ == k%length) break; } //因为k%length < length,所以e肯定为空,不过为了保险,下边判断的时候可以加入 while(p&e&e->next) while(p && e && e->next){ p = p->next; e = e->next; } if (p) { h->next = p->next; p->next = NULL; } if (e) e->next = head; return h->next; } };