148. Sort List

Description

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

Solution

Merge-sort, time O(n logn), space O(1)

/**
 * 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;
        }
        // divide
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode second = slow.next;
        slow.next = null;
        // conquer
        head = sortList(head);
        second = sortList(second);
        // combine
        return mergeSortedList(head, second);
    }
    
    public ListNode mergeSortedList(ListNode p, ListNode q) {
        if (p == null) {
            return q;
        }
        if (q == null) {
            return p;
        }
        
        if (p.val <= q.val) {
            p.next = mergeSortedList(p.next, q);
            return p;
        } else {
            q.next = mergeSortedList(p, q.next);
            return q;
        }
    }
}

你可能感兴趣的:(148. Sort List)