LeetCode——21. Merge Two Sorted Lists

博客介绍了合并两个有序链表并返回新链表的方法。给出了示例,如输入1->2->4和1->3->4,输出为1->1->2->3->4->4。还介绍了两种算法实现,一种是通过while循环迭代,另一种是递归,递归速度稍快但空间占用多。

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

LeetCode——21. Merge Two Sorted Lists


合并两个有序的列表,使之产生一个有序的新列表

Description

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.

Examples

Example:

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

Algorithm

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = None
        if l1 is None and l2 is None:
            return head
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        if l1.val <= l2.val:
            head = ListNode(l1.val)
            l1 = l1.next
        else:
            head = ListNode(l2.val)
            l2 = l2.next
        
        nexts = head
        
        while l1 is not None or l2 is not None:
            if l1 is None:
                nexts.next = ListNode(l2.val)
                l2 = l2.next
            elif l2 is None:
                nexts.next = ListNode(l1.val)
                l1 = l1.next
            elif l1.val <= l2.val:
                nexts.next = ListNode(l1.val)
                l1 = l1.next
            else:
                nexts.next = ListNode(l2.val)
                l2 = l2.next
            nexts = nexts.next
        return head

Note

可以通过while循环迭代的方式实现此算法,首先判断两个列表是否为空,如果为空则直接返回空,或者直接返回不为空的列表。在两个列表不为空的情况下通过while循环,挨个比较两个列表的值,产生新的节点。

Algorithm-Recursive

还可以通过递归来实现该算法,递归在速度上和之前的迭代差不太多,快了大约2%,但是在空间占用上多了13%多,但是算法简单易懂。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None:
            return l2
        if l2 is None:
            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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值