https://leetcode-cn.com/problems/sort-list/

    • 笔试的时候直接申请一个数组,然后把链表中每个节点都加到数组里去,然后排序数组,最后再重新把链表串起来

    进阶:

    • 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

    两个链表在merge的时候不涉及数组的覆盖问题,所以是可以做到空间复杂度O(1)

    1. /**
    2. * 法二:自底向上的归并排序 时间复杂度O(nlogn), 空间复杂度O(1)
    3. */
    4. public ListNode sortList2(ListNode head) {
    5. if (head == null) {
    6. return head;
    7. }
    8. int length = 0;
    9. ListNode cur = head;
    10. while (cur != null) {
    11. cur = cur.next;
    12. length++;
    13. }
    14. ListNode dummy = new ListNode(0, head);
    15. //步长
    16. for (int subLength = 1; subLength < length; subLength <<= 1) {
    17. ListNode prev = dummy;
    18. cur = dummy.next;
    19. while (cur != null) {
    20. ListNode head1 = cur;
    21. for (int i = 1; i < subLength && cur.next != null ; i++){
    22. cur = cur.next;
    23. }
    24. ListNode head2 = cur.next;
    25. cur.next = null;
    26. cur = head2;
    27. for (int i = 1; i < subLength && cur != null && cur.next != null; i++) {
    28. cur = cur.next;
    29. }
    30. ListNode next = null;
    31. if (cur != null) {
    32. next = cur.next;
    33. cur.next = null;
    34. }
    35. ListNode merged = merge(head1, head2);
    36. prev.next = merged;
    37. while (prev.next != null) {
    38. prev = prev.next;
    39. }
    40. cur = next;
    41. }
    42. }
    43. return dummy.next;
    44. }
    45. private ListNode merge(ListNode node1, ListNode node2) {
    46. ListNode dummy = new ListNode(0);
    47. ListNode cur = dummy;
    48. while (node1 != null && node2 != null) {
    49. if (node1.val <= node2.val) {
    50. cur.next = node1;
    51. node1 = node1.next;
    52. } else {
    53. cur.next = node2;
    54. node2 = node2.next;
    55. }
    56. cur = cur.next;
    57. }
    58. if (node1 != null) {
    59. cur.next = node1;
    60. }
    61. if (node2 != null) {
    62. cur.next = node2;
    63. }
    64. return dummy.next;
    65. }