首页 > 代码库 > Rotate List
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
.
分析:此题问的不是很明确,所以理解题意很重要,特别是k大于list长度的时候。
class Solution {public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || head->next == NULL) return head; int len = 0; for(ListNode * p = head; p; p = p->next, len++); if(len == k) return head; k = k%len; if(k == 0) return head; ListNode * first = head, *second = head; for(int i = 0; i < k-1; i++,second = second->next); ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode * pre_first = dummy; while(second->next){ pre_first = first; first = first->next; second = second->next; } second->next = dummy->next; pre_first->next = NULL; dummy->next = first; return dummy->next; }};
Rotate List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。