21. Merge two sorted lists

Merge two sorted linked lists and return it as a sorted list.

  • code better
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # Creates a placeholder for the result.
        dummy_head = tail = ListNode()

        while l1 and l2:
            if l1.val < l2.val:
                tail.next, l1 = l1, l1.next
            else:
                tail.next, l2 = l2, l2.next
            tail = tail.next

        # Appends the remaining nodes of L1 or L2
        tail.next = l1 or l2
        return dummy_head.next

  • code own first.. in place
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # if not l1 and not l2:
            # return None
        if not l1 or not l2:
            return l1 if l1 else l2
        if l1.val > l2.val:
            l1, l2 = l2, l1
        res = dumpl1 = ListNode(0, l1)
        while dumpl1.next or l2:
            if not dumpl1.next:
                dumpl1.next = l2
                return res.next
            if not l2:
                return res.next
            if dumpl1.next.val < l2.val:
                dumpl1 = dumpl1.next
            else:
                dumpl1.next = ListNode(l2.val, dumpl1.next)
                l2 = l2.next
        return res.next