题目

image.png

思路

  • 由于要实现O(nlogn)的时间复杂度,所以需要使用归并排序来进行排序,归并排序的每次找到链表的中点,将链表切割成两段,直到长度为1,此时在合并每段代码

    代码

    1. public ListNode sortList(ListNode head) {
    2. if (head == null || head.next == null) return head;
    3. return mergeSort(head);
    4. }
    5. public ListNode mergeSort(ListNode head) {
    6. if (head.next == null) return head;
    7. ListNode fast = head.next, slow = head;
    8. while (fast != null && fast.next != null) {
    9. fast = fast.next.next;
    10. slow = slow.next;
    11. }
    12. fast = slow.next;
    13. slow.next = null;
    14. return merge(mergeSort(head), mergeSort(fast));
    15. }
    16. public ListNode merge(ListNode p1, ListNode p2) {
    17. ListNode dummy = new ListNode(0);
    18. ListNode p = dummy;
    19. while (p1 != null && p2 != null) {
    20. if (p1.val < p2.val) {
    21. p.next = p1;
    22. p1 = p1.next;
    23. } else {
    24. p.next = p2;
    25. p2 = p2.next;
    26. }
    27. p = p.next;
    28. }
    29. p.next = p1 == null ? p2 : p1;
    30. return dummy.next;
    31. }

    排序链表