Sort by

recency

|

990 Discussions

|

  • + 0 comments

    Python code:

    def mergeLists(head1, head2):

    dummy = SinglyLinkedListNode(0)
    
    current = dummy   
    
    while head1 is not None and head2 is not None:
    
        if head1.data < head2.data:
    
            current.next = head1
    
            head1 = head1.next      
    
        elif head1.data == head2.data:
    
            current.next = head1
    
            head1 = head1.next
    
            current = current.next
    
            current.next = head2
    
            head2 = head2.next      
    
        else:
    
            current.next = head2
    
            head2 = head2.next     
    
        current = current.next
    
        # Attach remaining nodes from either list
    
    if head1 is not None:
    
            current.next = head1
    elif head2 is not None:
            current.next = head2
    
    return dummy.next
    
  • + 0 comments

    Python code:

    def mergeLists(head1, head2):

    if head1 is None:
        return head2
    if head2 is None:
        return head1
    
    if (head1.data < head2.data):
        head1.next = mergeLists(head1.next, head2)
        return head1
    else:
        head2.next = mergeLists(head2.next, head1)
        return head2
    
  • + 0 comments

    def mergeLists(head1, head2): dummy = SinglyLinkedListNode(0) tail = dummy

    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
    
    tail.next = head1 if head1 else head2
    return dummy.next
    
  • + 0 comments

    Problem explanation is incorrect in the example. There is no 7 in either input LinkedList.

  • + 0 comments

    Merging two sorted linked lists is a classic linked list problem, often asked in technical interviews and widely used in algorithms like merge sort. Cricbet99 Green Sign Up