Merge two sorted linked lists

  • + 0 comments
    def mergeLists(head1, head2):
        dummy = SinglyLinkedListNode(0)         # A dummy node to start the merged list
        tail = dummy            # Tail is where we add new nodes
    
        while head1 and head2:
            if head1.data <= head2.data:
                tail.next = head1
                head1 = head1.next
            else:
                tail.next = head2
                head2 = head2.next
            tail = tail.next    # Move tail forward
    
        # Attach the rest of the non-empty list
        if head1:
            tail.next = head1
        elif head2:
            tail.next = head2
    
        return dummy.next