【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 

原文地址:https://www.cnblogs.com/kwangeline/p/5953561.html