148. 排序链表

2022-10-26 18:12:54 浏览数 (1)

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

代码语言:javascript复制
输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

代码语言:javascript复制
输入: -1->5->3->4->0
输出: -1->0->3->4->5

解:归并

代码语言:javascript复制
/**
 * 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 prev = null;
        ListNode slow = head;
        ListNode fast = head;

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

        prev.next = null;

        //排序
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);

        //合并
        return merge(l1, l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode l = new ListNode(0);
        ListNode p = l;

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

        if (l1 != null)
            p.next = l1;

        if (l2 != null)
            p.next = l2;

        return l.next;
    }
}

0 人点赞