Leetcode: 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.

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(head == NULL || k <= 0)
15             return head;
16         int length = 0;
17         ListNode *temp = head;
18         while(temp)
19         {
20             length ++;
21             temp = temp -> next;
22         }
23         k = k % length;
24         
25         ListNode *fast = head;
26         ListNode *slow = head;
27         int i = 1;
28         for(;i <= k; i++)
29         {
30             fast = fast -> next;
31         }
32         for (;i < length; i++)
33         {
34             fast = fast -> next;
35             slow = slow -> next;
36         }
37         fast -> next = head;
38         head = slow -> next;
39         slow -> next = NULL;
40         
41         return head;
42         
43     }
44 };

 

posted @ 2013-05-02 14:12  caijinlong  阅读(134)  评论(0编辑  收藏  举报