首页 > 其他 > 详细

Rotate List

时间:2016-08-06 08:31:17      阅读:193      评论:0      收藏:0      [点我收藏+]

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.

 

Runtime: 12ms.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* rotateRight(ListNode* head, int k) {
12         if(!head || !head->next) return head;
13         
14         // first find the (n - k % n)th element
15         ListNode* move = head;
16         int count = 1;
17         while(move->next) {
18             count++;
19             move = move->next;
20         }
21         ListNode* endNode = move;
22         
23         k %= count;
24         move = head;
25         int index = 0;
26         while(index++ < k)
27             move = move->next;
28     
29         ListNode* current = head;
30         while(move->next) {
31             move = move->next;
32             current = current->next;
33         }
34         endNode->next = head;
35         head = current->next;
36         current->next = NULL;
37        
38         return head;
39     }
40 };

 

Rotate List

原文:http://www.cnblogs.com/amazingzoe/p/5743247.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!