Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

148. Sort List #336

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

148. Sort List

Given the head of a linked list, return the list after sorting it in ascending order.

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

Example 1

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Example 3

Input: head = []
Output: []

Constraints

Tcdian commented 3 years ago

Solution

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function sortList(head: ListNode | null): ListNode | null {
    if (head === null || head.next === null) {
        return head;
    }
    let guard: ListNode | null = new ListNode(-1, head);
    let slow: ListNode | null = guard;
    let fast: ListNode | null = guard;
    while(fast !== null && fast.next !== null) {
        fast = fast.next.next;
        slow = slow!.next;
    }
    const rightList = slow!.next;
    slow!.next = null;
    const leftList = guard.next;
    let leftSorted = sortList(leftList);
    let rightSorted = sortList(rightList);
    guard.next = null;
    let patrol = guard;
    while (leftSorted !== null && rightSorted !== null) {
        if (leftSorted.val <= rightSorted.val) {
            patrol.next = leftSorted;
            leftSorted = leftSorted.next;
        } else {
            patrol.next = rightSorted;
            rightSorted = rightSorted.next;
        }
        patrol = patrol.next;
        patrol.next = null;
    }
    patrol.next = leftSorted || rightSorted;
    return guard.next;
};