21. Merge Two Sorted Lists

这是一个关于数据结构和算法的问题,具体是实现一个Python函数,将两个已按非递减顺序排列的链表合并成一个新的有序链表并返回。示例中给出了不同输入情况下的输出,包括空链表和包含0节点的链表。解决方案通过比较两个链表的节点值,依次合并到新的链表中,确保结果仍然有序。
摘要由CSDN通过智能技术生成

21. Merge Two Sorted Lists

Easy

6449754Add to ListShare

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

 

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]

 

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both l1 and l2 are sorted in non-decreasing order.
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None:
            return l2
        if l2 is None:
            return l1

        head_node = cur_node = None
        while l1 and l2:
            node = None
            if l1.val < l2.val:
                node = l1
                l1 = l1.next
            else:
                node = l2
                l2 = l2.next

            if head_node is None:
                head_node = cur_node = node
            else:
                cur_node.next = node
                cur_node = node

        while l1:
            cur_node.next = l1
            cur_node = l1
            l1 = l1.next
        while l2:
            cur_node.next = l2
            cur_node = l2
            l2 = l2.next

        return head_node

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值