LeetCode 21 合并两个有序链表

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

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

1. 遍历

题目很简单,直接遍历就完事儿了

var mergeTwoLists = function (l1, l2) {
    const prehead = new ListNode(-1);
    let pre = prehead;
    while(l1 != null && l2 != null) {
        if(l1.val < l2.val) {
            pre.next = l1;
            l1 = l1.next;
        } else {
            pre.next = l2;
            l2 = l2.next;
        }
        pre = pre.next;
    }
    pre.next = l1 === null ? l2 : l1;
    return prehead.next;
}

2. 递归

使用递归来写的话方便很多,能够减少很多的代码量。时间复杂度为 O(n+m),空间复杂度为 O(n+m)。

/**
 * 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;
    } else if (l2 === null) {
        return l1;
    } else if(l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    } else {
        l2.next = mergeTwoLists(l1, l2.next);
        return l2;
    }
};
原文地址:https://www.cnblogs.com/ssaylo/p/13371054.html