Merge two sorted linked lists

  • + 0 comments

    Bit hacky but...

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