Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第二十一题 - 合并两个有序链表 #22

Open
laizimo opened this issue Jun 6, 2020 · 0 comments
Open

第二十一题 - 合并两个有序链表 #22

laizimo opened this issue Jun 6, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented Jun 6, 2020

题目描述

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

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

算法

迭代

答案

/**
 * 迭代
 */
var mergeTwoLists = function(l1, l2) {
    // #1 创建链表
    const res = head = {};
    // #2 遍历链表
    while (l1 && l2) {
        // #3 判断l1节点和l2节点的大小,把小的节点赋值给head节点,然后移动链表
        if (l1.val > l2.val) {
            head.next = l2;
            l2 = l2.next;
        } else {
            head.next = l1;
            l1 = l1.next;
        }
        // #4 移动head节点
        head = head.next;
    }
    // #5 直接把后续的链表赋值给head节点
    head.next = l1 === null ? l2 : l1;
    return res.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant