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
            
  • 相关阅读:
    转换方法
    数组去重
    js常见兼容
    封装cookie
    常用函数封装
    手绘 代码
    Python变量和数据类型,类型转换
    语句块的概念及注释符的使用
    ipython和pip,模块安装方法
    第一个python程序
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10997293.html
Copyright © 2011-2022 走看看