Sort by

recency

|

988 Discussions

|

  • + 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

  • + 0 comments
        static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
    
             SinglyLinkedListNode newList = null;
    
        if(head1.data < head2.data){
            newList = new SinglyLinkedListNode(head1.data);
            head1 = head1.next;
        }else{
            newList = new SinglyLinkedListNode(head2.data);
            head2 = head2.next;
        }
    
        var head = newList;
    
        while(head1 != null && head2 != null){
    
            if(head1.data < head2.data){
                newList.next = new SinglyLinkedListNode(head1.data);
                head1 = head1.next;
            }else{
                newList.next = new SinglyLinkedListNode(head2.data);
                head2 = head2.next;
            }
            newList = newList.next;
        }
        newList.next = (head1 != null) ? head1 : head2;
    
    
        return head;
    }
    
  • + 0 comments

    Hi all, here my recursive solution in Java 8.

        static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            if(head1== null && head2== null)
                return null;
            if(head1 == null)
                return head2;
            if(head2 == null) {
                return head1;
            }
            SinglyLinkedListNode result = null;
            if(head1.data< head2.data){
                result = head1;
                result.next = mergeLists(head1.next, head2);
            } else {
                result = head2;
                result.next = mergeLists(head1, head2.next);
            } 
            
            return result;
        }