力扣算法题—148sort-list

 

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

Solution:
  复杂度为O(nlogn)有快速排序,并归排序,堆排序,对于来列表而言,堆排序最适合了
  使用快慢指针将链表分为两部分
  merge01为简洁版
 1 class Solution {
 2 public:
 3     ListNode* sortList(ListNode* head) {
 4         if (head == nullptr || head->next == nullptr)return head;
 5         ListNode *slow = head, *fast = head, *pre = head;
 6         while (fast != nullptr && fast->next != nullptr)
 7         {
 8             pre = slow;
 9             slow = slow->next;
10             fast = fast->next->next;
11         }
12         pre->next = nullptr;//将链表分为两段
13         return merge(sortList(head), sortList(slow));
14     }
15     ListNode* merge01(ListNode* l1, ListNode* l2)
16     {
17         if (l1 == nullptr || l2 == nullptr)return l1 == nullptr ? l2 : l1;
18         if (l1->val < l2->val)
19         {
20             l1->next = merge(l1->next, l2);
21             return l1;
22         }
23         else
24         {
25             l2->next = merge(l1, l2->next);
26             return l2;
27         }
28     }
29     ListNode* merge02(ListNode* l1, ListNode* l2)
30     {
31         ListNode* ptr = new ListNode(-1);
32         ListNode* p = ptr;
33         while (l1 != nullptr && l2 != nullptr)
34         {
35             if (l1->val < l2->val)
36             {
37                 p->next = l1;
38                 l1 = l1->next;
39             }
40             else
41             {
42                 p->next = l2;
43                 l2 = l2->next;
44             }
45             p = p->next;
46         }
47         if (l1 == nullptr)p->next = l2;
48         if (l2 == nullptr)p->next = l1;
49         return ptr->next;
50     }
51 };

 

posted @ 2019-10-30 22:05  自由之翼Az  阅读(197)  评论(0编辑  收藏  举报