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. public class Solution {
  4. public ListNode sortList(ListNode head) {
  5. if (head == null || head.next == null)return head;
  6. final ListNode middle = findMiddle(head);
  7. final ListNode head2 = middle.next;
  8. middle.next = null; // 断开
  9. final ListNode l1 = sortList(head); // 前半段排序
  10. final ListNode l2 = sortList(head2); // 后半段排序
  11. return mergeTwoLists(l1, l2);
  12. }
  13. // Merge Two Sorted Lists
  14. private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  15. ListNode dummy = new ListNode(-1);
  16. for (ListNode p = dummy; l1 != null || l2 != null; p = p.next) {
  17. int val1 = l1 == null ? Integer.MAX_VALUE : l1.val;
  18. int val2 = l2 == null ? Integer.MAX_VALUE : l2.val;
  19. if (val1 <= val2) {
  20. p.next = l1;
  21. l1 = l1.next;
  22. } else {
  23. p.next = l2;
  24. l2 = l2.next;
  25. }
  26. }
  27. return dummy.next;
  28. }
  29. // 快慢指针找到中间节点
  30. private static ListNode findMiddle(ListNode head) {
  31. if (head == null) return null;
  32. ListNode slow = head;
  33. ListNode fast = head.next;
  34. while (fast != null && fast.next != null) {
  35. slow = slow.next;
  36. fast = fast.next.next;
  37. }
  38. return slow;
  39. }
  40. }

相关题目

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