148 Sort List

1. Question

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

2. Implementation

(1) Top down merge sort

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode slow = head, fast = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode p = slow.next;
        slow.next = null;

        ListNode l1 = sortList(head);
        ListNode l2 = sortList(p);

        return merge(l1, l2);
    }

    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode curNode = dummy;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                curNode.next = l1;
                l1 = l1.next;
            }
            else {
                curNode.next = l2;
                l2 = l2.next;
            }
            curNode = curNode.next;
        }

        while (l1 != null) {
            curNode.next = l1;
            l1 = l1.next;
            curNode = curNode.next;
        }

        while (l2 != null) {
            curNode.next = l2;
            l2 = l2.next;
            curNode = curNode.next;
        }

        return dummy.next;
    }
}

(2) Bottom up merge sort

3. Time & Space Complexity

Top down merge sort:时间复杂度O(nlogn), 空间复杂度O(logn)

Bottom up merge sort: 时间复杂度O(nlogn), 空间复杂度O(1)

Last updated

Was this helpful?