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