Merge two sorted linked lists

  • + 0 comments

    Python3. Hope they don't mind me reusing their list class :P

    def mergeLists(
        head_1: SinglyLinkedListNode | None,
        head_2: SinglyLinkedListNode | None
    ) -> SinglyLinkedListNode | None:
        merged = SinglyLinkedList()
        
        while head_1 or head_2:
            min_head = min(
                (head_1, head_2),
                key=lambda head: head.data if head else float('inf')
            )
            
            merged.insert_node(min_head.data)
            
            # iterate the source list
            if min_head == head_1:
                head_1 = head_1.next
            else:
                head_2 = head_2.next
                
        return merged.head