• + 0 comments

    Two ways

    def mergeLists(head1, head2):
        l, result = [], SinglyLinkedList()
        while head1:
            l.append(head1.data)
            head1 = head1.next
        while head2:
            l.append(head2.data)
            head2 = head2.next
        for data in sorted(l):
            result.insert_node(data)
        return result.head
    
    def mergeLists(head1, head2):
        result = SinglyLinkedList()
        while head1 or head2:
            if not head1:
                result.insert_node(head2.data)
                head2 = head2.next
            elif not head2:
                result.insert_node(head1.data)
                head1 = head1.next
            elif head1 and head2:
                if head1.data <= head2.data:
                    result.insert_node(head1.data)
                    head1 = head1.next
                else:
                    result.insert_node(head2.data)
                    head2 = head2.next
        return result.head