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

21. 合并两个有序链表 #7

Open
Geekhyt opened this issue Jan 25, 2021 · 1 comment
Open

21. 合并两个有序链表 #7

Geekhyt opened this issue Jan 25, 2021 · 1 comment
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jan 25, 2021

原题链接

说起递归,大家可以看下我之前整理的这篇文章,你真的懂递归吗?

题目描述

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

示例:

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

思路

1.使用递归来解题
2.将两个链表头部较小的一个与剩下的元素合并
3.当两条链表中的一条为空时终止递归

关键点

  • 掌握链表数据结构
  • 考虑边界情况

复杂度分析

n+m是两条链表的长度

  • 时间复杂度:O(m+n)
  • 空间复杂度:O(m+n)
const 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
    }
}
@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
@GTRgoSky
Copy link

// 在选择方法上总是不一致,为什么这题选递归更好呢
/*
 * @lc app=leetcode.cn id=21 lang=javascript
 * 
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let l1 = list1,l2=list2;
    const prev = new ListNode(0);
    let cur = prev;
    while(l1 && l2) {
        if (l1.val > l2.val) {
            cur.next = l2;
            l2 = l2.next;
        } else {
            cur.next = l1;
            l1 = l1.next;
        }
        cur = cur.next;
    }
    cur.next = l1 || l2;
    return prev.next;
};
// @lc code=end


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants