leetcode 21. Merge Two Sorted Lists 递归和迭代 python3

本文详细介绍了如何将两个已排序的链表合并成一个新的有序链表。提供了两种方法:非递归方法通过迭代实现,而递归法则通过递归调用简化代码。每种方法都附有Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题描述

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

二.解题思路

就是把两个有序的列表合成一个有序的链表:

1.非递归方法:

如果l1和l2都为空,返回空链表。

创建一个空头head,然后再用一个变量记录这个头。

否则,开始迭代:

<1.判断l1和l2都不空并且l1的值小于l2或者l1不空l2空

此时下一个插入点是l1的当前节点。

插入完将更新l1和head至他们下一个节点。

<2.不满足1,则为插入2

<3.剪枝操作,若l1或者l2某一个是空,可以返回了

2.递归法

和上面差不多。

判断当前节点哪个小,然后让当前节点的next指向子递归。

用递归就是要弄清递归的返回条件和分割条件。

分割来说,对当前递归来说,之后的节点已经被组成了一个有序的链表,我只需决定我当前从l1和l2中选哪一个节点做我的当前节点,然后让其指向下一次递归返回的结果。具体看一下代码把。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.迭代

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#58
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 and not l2:return
        head=ListNode(0)
        root=head
        while l1 or l2:
            if l1 and l2 and l1.val <l2.val or l1 and not l2:
                head.next=l1
                l1=l1.next
            else:
                head.next=l2
                l2=l2.next
            if not l1 or not l2:break
            head=head.next
        return root.next

2.递归

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#58
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 and not l2: return None
        if not l1:return l2
        if not l2:return l1
        head=ListNode(0)
        if l1.val<l2.val:
            head=l1
            head.next=self.mergeTwoLists(l1.next,l2)
        else:
            head=l2
            head.next=self.mergeTwoLists(l1,l2.next)
        return head

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值