Leetcode 分享筆記

21. Merge Two Sorted Lists

題目

leetcode
b

python


class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ans = ListNode(None)
        prev = ans 
        while l1 and l2:
            if(l1.val <= l2.val):
                prev.next = l1
                l1 = l1.next
            else:
                prev.next = l2
                l2 = l2.next
            prev = prev.next
        if l1 == None:
            prev.next = l2
        if l2 == None:
            prev.next = l1
        return ans.next