【鏈表】鏈表排序

一、題目

力扣原題:https://leetcode-cn.com/problems/sort-list/

二、歸併排序

/**
 * 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 (null == head) {
            return null;
        }
        return split(head);
    }

    private ListNode split(ListNode node) {
        if (null == node || null == node.next) {
            return node;
        }

        // 雙指針,標記鏈表中點
        ListNode slow = node;
        ListNode fast = node.next;
        while (null != fast && null != fast.next) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // 鏈表分割
        ListNode pre = node;
        ListNode post = slow.next;
        slow.next = null;

        // 遞歸分割
        ListNode left = split(pre);
        ListNode right = split(post);
        return merge(left, right);
    }

    private ListNode merge(ListNode pre, ListNode post) {
        ListNode node = new ListNode(-1);
        ListNode cur = node;
        while (null != pre && null != post) {
            if (pre.val <= post.val) {
                cur.next = new ListNode(pre.val);
                pre = pre.next;
            } else {
                cur.next = new ListNode(post.val);
                post = post.next;
            }
            cur = cur.next;
        }

        if (null != pre) {
            cur.next = pre;
        }

        if (null != post) {
            cur.next = post;
        }
        return node.next;
    }
}
  • 時間複雜度:O(nlog(n))
  • 空間複雜度:O(log(n))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章