• + 0 comments

    An iterative solution in Python

    def mergeLists(head1, head2):
        merged_list = SinglyLinkedList()
        while(head1 is not None and head2 is not None):
            if head1.data < head2.data:
                merged_list.insert_node(head1.data)
                head1 = head1.next
            elif head1.data > head2.data:
                merged_list.insert_node(head2.data)
                head2 = head2.next
            else:
                merged_list.insert_node(head1.data)
                merged_list.insert_node(head2.data)
                head1 = head1.next
                head2 = head2.next
        while(head1 is not None):
            merged_list.insert_node(head1.data)
            head1 = head1.next
        while(head2 is not None):
            merged_list.insert_node(head2.data)
            head2 = head2.next
        return merged_list.head