Merge Two Sorted List

本文介绍了一种将两个已排序的链表合并为一个新排序链表的方法。通过创建一个虚拟头节点简化新链表的构造过程。算法遍历两个输入链表,比较节点值并依次连接较小值节点,直至其中一个链表遍历完毕。

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Tag

LinkedList

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Easy Solution

Create a dummy node at head, convenient for creating a new linked list

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
    var start1 = l1, start2 = l2;
    var ret = [];

    while (start1 && start2) {
        if (start1.val < start2.val) {
            ret.push(start1.val);
            start1 = start1.next;
        } else {
            ret.push(start2.val);
            start2 = start2.next;
        }
    }

    while (start1) {
        ret.push(start1.val);
        start1 = start1.next;
    }

    while (start2) {
        ret.push(start2.val);
        start2 = start2.next;
    }

    return ret;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值