美文网首页
148. Sort List

148. Sort List

作者: jluemmmm | 来源:发表于2021-01-27 13:56 被阅读0次

    链表排序,使用归并排序

    • Runtime: 268 ms, faster than 17.27%
    • Memory Usage: 64.9 MB, less than 5.18%
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var sortList = function(head) {
        if(!head || !head.next) return head
        let fast = head
        let slow = head
        let prev = null
        while(fast && fast.next) {
            prev = slow
            fast = fast.next.next
            slow = slow.next
        }
        prev.next = null
        let l1 = sortList(head)
        let l2 = sortList(slow)
        
        return mergeTwoLists(l1, l2)
        
    };
    var mergeTwoLists = function(l1, l2) {
        let dummy = new ListNode(0)
        let res = dummy
        while(l1 && l2) {
            if(l1.val < l2.val) {
                res.next = new ListNode(l1.val)
                l1 = l1.next
            } else {
                res.next = new ListNode(l2.val)
                l2 = l2.next
            }
            res = res.next
        }
        if (l1) {
            res.next = l1
        } else {
            res.next = l2
        }
        return dummy.next
    };
    

    相关文章

      网友评论

          本文标题:148. Sort List

          本文链接:https://www.haomeiwen.com/subject/ihhlzktx.html