JS Merge Sort Runtime Error


  • 0
    I

    Reference Post

    I used exact the same approach as the post I linked above, but I got Runtime Error when submitting.

    My code is as below:

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var sortList = function(head) {
        
        return sort(head);
        
        function sort(node) {
            let pre, n1, n2, h1, h2;
            
            if (node === null || node.next === null) return node;
            n1 = node;
            n2 = node;
            
            while (n2 !== null && n2.next !== null) {
                pre = n1;
                n1 = n1.next;
                n2 = n2.next.next;
            }
            
            pre.next = null;
            
            h1 = sort(node);
            h2 = sort(n1);
            
            return merge(h1, h2);
        }
        
        function merge(node1, node2) {
            if (node1 === null) return node2;
            if (node2 === null) return node1;
            
            if (node1.val < node2.val) {
                node1.next = merge(node1.next, node2);
                return node1;
            }
            else {
                node2.next = merge(node1, node2.next);
                return node2;
            }
        }
    
    };
    

  • 0
    M

    Don't use recursion for your merge. You will overflow the callstack and it will cause runtime error.


Log in to reply
 

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