zoukankan      html  css  js  c++  java
  • 【leetcode❤python】21. Merge Two Sorted Lists

    #-*- coding: UTF-8 -*-
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    #Method1
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if l1==None:return l2
            if l2==None:return l1
            
            node=None
            
            while l1!=None and l2!=None:

                if l1.val<=l2.val:
                    if node==None:
                        node=l1
                        head=node
                    else:
                        node.next=l1
                        node=node.next
                    l1=l1.next
                else:
                  
                    if node==None:
                        node=l2
                        head=node
                    else:
                        node.next=l2
                        node=node.next
                    l2=l2.next
            
            node.next=l1 or l2
            return head
        
        
    #Method2
    class Solution:   
        def mergeTwoLists(self, l1, l2):  
            if not l1 and not l2:  
                return None  
     
            dummy = ListNode(0)  
            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  
     
            return dummy.next 

  • 相关阅读:
    0.1.3 set的用法
    JoinPoint
    砝码组合(dfs)
    强大的【环绕通知】
    applicationContext.xml 模板
    各种jar包
    装饰博客(二)添加宠物
    装饰博客(一)添加背景图片
    拖拽功能的实现
    点击之后连接qq
  • 原文地址:https://www.cnblogs.com/kwangeline/p/5953561.html
Copyright © 2011-2022 走看看