zoukankan      html  css  js  c++  java
  • leetcode21. 合并两个有序链表 🌟

    题目:

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

    示例:

      输入:1->2->4, 1->3->4
      输出:1->1->2->3->4->4

    来源:力扣(LeetCode)

    1 # Definition for singly-linked list.
    2 # class ListNode:
    3 #     def __init__(self, x):
    4 #         self.val = x
    5 #         self.next = None

    解答:

    leetcode优秀方案(来自力扣答案统计页,没有明确作者是谁,可留言告知):

    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            dummy = ListNode(None)
            cur = dummy
            while l1 and l2:
                if l1.val < l2.val:
                    cur.next = l1
                    l1 = l1.next
                else:
                    cur.next = l2
                    l2 = l2.next
                cur = cur.next
            
            # cur.next = l1 or l2
            if not l1:
                cur.next = l2
            if not l2:
                cur.next = l1
            
            return dummy.next
    View Code
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            if l1 and l2:
                if l1.val > l2.val: l1, l2 = l2, l1
                l1.next = self.mergeTwoLists(l1.next, l2)
            return l1 or l2
    # 作者:QQqun902025048
    # 链接:https://leetcode-cn.com/problems/two-sum/solution/python-4xing-by-knifezhu-3/
    View Code
  • 相关阅读:
    盘符格式转换成NTFS格式
    jdk环境变量配置
    修改mysql密码
    端口占用解决
    程序执行原理
    第一个Python程序
    pip安装第三方库失败的问题
    windows本地安装mongoDB并且安装可视化工具studio 3t
    开发时前端测试方法
    虚拟机配置vimrc
  • 原文地址:https://www.cnblogs.com/catyuang/p/11112660.html
Copyright © 2011-2022 走看看