• LeetCode 21. 合并两个有序链表


    21. 合并两个有序链表

    Difficulty: 简单

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

    示例 1:

    输入:l1 = [1,2,4], l2 = [1,3,4]
    输出:[1,1,2,3,4,4]
    

    示例 2:

    输入:l1 = [], l2 = []
    输出:[]
    

    示例 3:

    输入:l1 = [], l2 = [0]
    输出:[0]
    

    提示:

    • 两个链表的节点数目范围是 [0, 50]
    • -100 <= Node.val <= 100
    • l1l2 均按 非递减顺序 排列

    Solution

    初始化dummy链表res,遍历两个链表,两两比较链表的结点。注意不要落下没有比较完的剩余部分。

    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            res = ListNode(-1)
            p = res
            
            while l1 and l2:
                if l1.val >= l2.val:
                    p.next = l2
                    l2 = l2.next
                else:
                    p.next = l1
                    l1 = l1.next
                p = p.next
            p.next = l1 if l1 is not None else l2
            return res.next
    

    如果题目要求合并的链表不能有重复元素呢?

    # 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:
            res = ListNode(-1)
            p = res
            
            while l1 and l2:
                if l1.val > l2.val:
                    p.next = l2
                    l2 = l2.next
                elif l1.val < l2.val:
                    p.next = l1
                    l1 = l1.next
                else:
                    p.next = l1
                    l1 = l1.next
                    l2 = l2.next
                p = p.next
            p.next = l1 if l1 is not None else l2
            return res.next
    
  • 相关阅读:
    比较器 Comparable 与compartor 的区别及理解
    事务特性、事务隔离级别、spring事务传播特性
    分布式文件上传-FastDFS
    spring-cloud 组件总结以及搭建图示 (六)
    springCloud zuul网关(五)
    hashCode与equals 通过面试题一窥究竟
    【原】那年30岁
    【原】Hyper-V虚拟机设置外部网络访问
    【原】win10 .net framework 3.5安装
    【原】做梦有感
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14743151.html
Copyright © 2020-2023  润新知