algorithm icon indicating copy to clipboard operation
algorithm copied to clipboard

148. 排序链表

Open JesseZhao1990 opened this issue 6 years ago • 0 comments

image

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var sortList = function(head) {
    if(head == null || head.next == null) return head;
    let fast = head.next, slow = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next
    }
    let temp = slow.next;
    slow.next = null;

    let left = sortList(head)
    let right = sortList(temp)

    let h = new ListNode(0)
    let res = h
    while (left != null && right != null) {
        if (left.val < right.val) {
            h.next = left
            left = left.next
        } else {
            h.next = right
            right = right.next
        }
        h = h.next
    }
    h.next = left != null ? left : right
    return res.next

};

JesseZhao1990 avatar Nov 16 '19 05:11 JesseZhao1990