Skip to content

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

Description

@laizimo

题目描述

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

示例:
输入: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;
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions