「✍ Q: 链表合并」

715 阅读1分钟

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入: l1 = [1,2,4], l2 = [1,3,4]
输出: [1,1,2,3,4,4]
/**
 * 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
    }
    
    // 选出失败节点
    let head = l1.val < l2.val ? l1 : l2

    // 假设head = l1 , 则失败节点l1的下一个节点继续和l2比较
    head.next = mergeTwoLists(head.next, head === l1 ? l2 : l1)
    
    return head
};

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
   }