码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 61. Rotate List

时间:2015-03-15 18:21:30      阅读:114      评论: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.

[Solution]

tips: k might be large than list length, k = k % length

 1 ListNode *rotateRight(ListNode *head, int k) 
 2     {
 3         ListNode *fast = head, *slow = head;
 4         int i, len = 0;
 5         
 6         while (fast != NULL)
 7         {
 8             len++;
 9             fast = fast->next;
10         }
11         
12         if ((len <= 1) || ((k = k % len) == 0))
13             return head;
14         
15         fast = head;
16         for (i = 0; i < k; i++)
17             fast = fast->next;
18         while (fast->next != NULL)
19         {
20             fast = fast->next;
21             slow = slow->next;
22         }
23         fast->next = head;
24         head = slow->next;
25         slow->next = NULL;
26         
27         return head;
28     }

 

leetcode 61. Rotate List

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4340064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!