[路飞]_ LeetCode21. 合并两个有序链表

122 阅读1分钟

「这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战

LeetCode21. 合并两个有序链表

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

思路
1.要判断两个链表都不是空链表,否则就没有任何意义
if (l1 == null) return l2;
if (l2 == null) return l1;
2.判断哪个链表头节点的值更小,然后递归的决定下一个添加到结果里面的节点
if (l1.val < l2.val) {  
    l1.next = mergeTwoLists(l1.next,l2);  
    return l1;
} else {  
    l2.next = mergeTwoLists(l1,l2.next);  
    return l2;
}

完整代码

var mergeTwoLists = function(l1, l2) {    
    if (l1 === null) return l2;    
    if (l2 === null) return l1;    
    if (l1.val < l2.val) {        
        l1.next = mergeTwoLists(l1.next,l2);        
        return l1;    
    } else {        
        l2.next = mergeTwoLists(l1,l2.next);        
        return l2;    
    }
};