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

No.148 Sort List

时间:2015-05-25 18:00:34      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

No.148 Sort List

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

分析:

  常量空间且O(nlogn)时间复杂度,单链表适合用归并排序,双向链表适合用快速排序

  有一个问题是:若算上栈空间,空间复杂度也为O(nogn)

  还是对排序算法不够熟练!!

 

 1 struct ListNode
 2 {
 3     int val;
 4     ListNode *next;
 5     ListNode(int x):val(x),next(NULL){}
 6 };
 7 class Solution
 8 {
 9 public:
10     ListNode* sortList(ListNode* head)
11     {//单链表排序:要求时间复杂度为O(nlogn),空间复杂度为O(1)
12         if(head == NULL || head->next == NULL)//终止条件
13             return head;
14 
15         //快慢指针找到中间节点
16         ListNode *fast = head;
17         ListNode *slow = head;
18         //将链表分为两段,因为fast快,所以以它为判断条件
19         while(fast->next != NULL && fast->next->next != NULL)
20         {
21             slow = slow->next;
22             fast = fast->next->next;
23         }
24 
25         ListNode *second = slow->next;
26         slow->next = NULL;//断开链表
27         //错:sortList(head);
28         //错:sortList(second);
29         //错:MergeSortedList(head, second);
30         //错:return head;
31         ListNode *l1= sortList(head);
32         ListNode *l2 = sortList(second);
33         return MergeSortedList(l1, l2);
34     }
35 
36     ListNode* MergeSortedList(ListNode *first, ListNode *second)
37     {
38         if(first == NULL)
39             return second;
40         if(second == NULL)
41             return first;
42 
43         ListNode *head, *current;
44         if(first->val <= second->val)
45         {
46             head = first;
47             first = first->next;
48         }
49         else
50         {
51             head = second;
52             second = second->next;
53         }
54         current = head;
55 
56         while(first!= NULL && second != NULL)
57         {
58             if(first->val <= second->val)
59             {
60                 current->next = first;
61                 first = first->next;
62             }
63             else
64             {
65                 current->next = second;
66                 second = second->next;
67             }
68             current = current->next;
69         }
70 /*
      //注意与合并有序数组的区别
71 while(first != NULL) 72 { 73 current->next = first; 74 first = first->next; 75 current = current->next; 76 } 77 while(second != NULL) 78 { 79 current->next = second; 80 second = second->next; 81 current = current->next; 82 } 83 */ 84 if(first) 85 current->next = first; 86 if(second) 87 current->next = second; 88 89 return head; 90 } 91 };

 

No.148 Sort List

标签:

原文地址:http://www.cnblogs.com/dreamrun/p/4528182.html

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