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

Sort List

时间:2014-08-09 23:13:19      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   div   时间   amp   

Sort a linked list in O(n log n) time using constant space complexity.

思路:题目要求O(n log n)的时间复杂度以及常空间复杂度,因此,使用归并排序策略。

 1 class Solution {
 2 public:
 3     ListNode *sortList( ListNode *head ) {
 4         if( !head || !head->next ) { return head; }
 5         if( !head->next->next ) {
 6             if( head->val > head->next->val ) {
 7                 int temp = head->val;
 8                 head->val = head->next->val;
 9                 head->next->val = temp;
10             }
11             return head;
12         }
13         ListNode *slow = head, *fast = head->next;
14         while( fast->next ) {
15             slow = slow->next;
16             fast = fast->next;
17             if( fast->next ) { fast = fast->next; }
18         }
19         fast = slow->next; slow->next = 0;
20         slow = sortList( head );
21         fast = sortList( fast );
22         return merge( slow, fast );
23     }
24 private:
25     ListNode *merge( ListNode *slow, ListNode *fast ) {
26         if( !slow ) { return fast; }
27         if( !fast ) { return slow; }
28         ListNode *head = 0, *end = 0;
29         if( slow->val <= fast->val ) {
30             head = end = slow; slow = slow->next;
31         } else {
32             head = end = fast; fast = fast->next;
33         }
34         while( slow && fast ) {
35             if( slow->val <= fast->val ) {
36                 end->next = slow;
37                 end = end->next;
38                 slow = slow->next;
39             } else {
40                 end->next = fast;
41                 end = end->next;
42                 fast = fast->next;
43             }
44         }
45         if( slow ) { end->next = slow; }
46         else { end->next = fast; }
47         return head;
48     }
49 };

 

Sort List,布布扣,bubuko.com

Sort List

标签:style   blog   color   使用   io   div   时间   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3901725.html

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