Merge sort solution in Javascript.


  • 0
    X
    function mergeTwo (one, two) {
       var dummy = new ListNode(-1);
       var head = dummy;
       while(one && two) {
           if (one.val < two.val) {
               head.next = one;
               one = one.next;
           } else {
               head.next = two;
               two = two.next;
           }
           head = head.next;
       }
       if (one) head.next = one;
       if (two) head.next = two;
       return dummy.next;
    }
    function sortList (head) {
        if (!head || !head.next) return head;
        var fast = head, slow = head;
        while(fast.next && fast.next.next) {
            fast = fast.next.next;
            slow = slow.next;
        }
        var second = slow.next;
        slow.next = null;
        head = sortList(head);
        second = sortList(second);
        return mergeTwo(head, second);
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.