Sort List

描述

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

分析

常数空间且O(nlogn),单链表适合用归并排序,双向链表适合用快速排序。本题可以复用 Merge Two Sorted Lists 的代码。

代码

  1. // Sort List
  2. // 归并排序,时间复杂度O(nlogn),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *sortList(ListNode *head) {
  6. if (head == NULL || head->next == NULL)return head;
  7. ListNode *middle = findMiddle(head);
  8. ListNode *head2 = middle->next;
  9. middle->next = nullptr; // 断开
  10. ListNode *l1 = sortList(head); // 前半段排序
  11. ListNode *l2 = sortList(head2); // 后半段排序
  12. return mergeTwoLists(l1, l2);
  13. }
  14. private:
  15. // Merge Two Sorted Lists
  16. static ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
  17. ListNode dummy(-1);
  18. for (ListNode* p = &dummy; l1 != nullptr || l2 != nullptr; p = p->next) {
  19. int val1 = l1 == nullptr ? INT_MAX : l1->val;
  20. int val2 = l2 == nullptr ? INT_MAX : l2->val;
  21. if (val1 <= val2) {
  22. p->next = l1;
  23. l1 = l1->next;
  24. } else {
  25. p->next = l2;
  26. l2 = l2->next;
  27. }
  28. }
  29. return dummy.next;
  30. }
  31. // 快慢指针找到中间节点
  32. static ListNode* findMiddle(ListNode* head) {
  33. if (head == nullptr) return nullptr;
  34. ListNode *slow = head;
  35. ListNode *fast = head->next;
  36. while (fast != nullptr && fast->next != nullptr) {
  37. slow = slow->next;
  38. fast = fast->next->next;
  39. }
  40. return slow;
  41. }
  42. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/sorting/merge-sort/sort-list.html