• 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
  • 相关阅读:
    koa2 中间件里面的next到底是什么
    nodejs 之 nvm和pm2
    javascript瀑布流
    转使用chrome命令行:disable
    MariaDB 用户与授权
    MariaDB TRANSACTION
    IHS .kdb转crt,key
    MariaDB TRIGGER
    MariaDB CURSOR
    MariaDB PROCEDURE
  • 原文地址:https://www.cnblogs.com/catyuang/p/11112660.html
Copyright © 2020-2023  润新知