leetcode21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

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

Input: list1 = [1,2,4], list2 = [1,3,4]

Output: [1,1,2,3,4,4]

思路:递归

python 复制代码
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1: return l2  # 终止条件,直到两个链表都空
        if not l2: return l1
        if l1.val <= l2.val:  # 递归调用
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
相关推荐
NAGNIP35 分钟前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP1 小时前
一文搞懂机器学习中的特征构造!
算法·面试
梨落秋霜1 小时前
Python入门篇【文件处理】
android·java·python
Java 码农1 小时前
RabbitMQ集群部署方案及配置指南03
java·python·rabbitmq
Learn Beyond Limits1 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长2 小时前
C语言---typedef
c语言·c++·算法
张登杰踩3 小时前
VIA标注格式转Labelme标注格式
python
Qhumaing3 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
Learner3 小时前
Python数据类型(四):字典
python