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
  • 相关阅读:
    23.Java函数
    22.java中的break和continue关键字
    21.Java中for循环
    20.java中的while循环
    19.java中选择判断语句(switch)
    18.java中判断(if…else)
    17.java运算符的优先级与结合性
    16.Java三元运算符
    数组去重
    数组 字符串 对象 常用方法
  • 原文地址:https://www.cnblogs.com/catyuang/p/11112660.html
Copyright © 2011-2022 走看看