`

Sort List

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

在O(nlogn)的时间复杂度下对一个链表进行排序,通过时间复杂度很容易想到用快排和分治。链表的快排实现比较复杂,这里我们用分治法来实现。代码如下:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode node = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(node);
        return merge(left, right);
    }
    public ListNode merge(ListNode left, ListNode right) {
        if(left == null) return right;
        if(right == null) return left;
        if(left.val > right.val) {
            right.next = merge(left, right.next);
            return right;
        } else {
            left.next = merge(left.next, right);
            return left;
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics