zoukankan      html  css  js  c++  java
  • leetcode-easy-listnode-21 merge two sorted lists

    mycode

    一定要记得创建两个头哦,一个找路,一个找家

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            l = dummy = ListNode(-1)
            while l1 or l2:
                if not l1:
                    l.next = l2
                    break
                elif not l2:
                    l.next = l1
                    break
                if l1.val < l2.val:
                    l.next = l1
                    l1 = l1.next
                else:
                    l.next = l2
                    l2 = l2.next
                l = l.next
            return dummy.next

    参考

    下面这个更快

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            
            res = temp = ListNode(0)
            
            while l1 or l2:
                v1 = v2 = float('inf')
                if l1 is not None: v1 = l1.val
                if l2 is not None: v2 = l2.val
                if v1 > v2:
                    temp.next = l2
                    l2 = l2.next
                else:
                    temp.next = l1
                    l1 = l1.next
                temp = temp.next
            
            return res.next
            
  • 相关阅读:
    最长公共子序列(LCS)
    数组分割问题
    Trie树
    BitMap(比特位)
    KMP算法——字符串匹配
    排序算法
    概率问题
    【设计模式】——访问者模式
    【设计模式】——解释器模式
    【设计模式】——享元模式
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10997293.html
Copyright © 2011-2022 走看看