Merges two ascending lists into a new ascending list and returns. A new list is formed by concatenating all the nodes of a given two lists.

Input: l1 = [1,2,4], l2 = [1,3,4]Copy the code
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * * *@param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}* /
var mergeTwoLists = function(l1, l2) {
    
    if(l1 === null) {
        return l2
    }

    if(l2 === null) {return l1
    }
    
    // Select the failed node
    let head = l1.val < l2.val ? l1 : l2

    // If head = l1, the next node of failed node L1 continues to be compared with L2
    head.next = mergeTwoLists(head.next, head === l1 ? l2 : l1)
    
    return head
};

Copy the code

e.g

    l1 = [1.3]
    l2 = [2.4]
    
   {
       head = 1
       1.next = mergeTwoLists(3.2)
       return 1
   }

   {
       head = 2
       2.next = mergeTwoLists(3.4)
       return 2
   }
   {
       head = 3
       3.next = mergeTwoLists(null.4)
       return 3
   }
   {
     l1 === null
     return 4
   }
Copy the code