Merge two sorted linked lists

Sort by

recency

|

204 Discussions

|

  • + 0 comments

    The problem is not available to be solved in Swift.

  • + 0 comments

    This is my solution using Python3. This solution is inspired by the technique used in mergesort to combine 2 sorted lists.

    def mergeLists(head1, head2):
        # Checking if any linkedlist is empty
        if not head1:
            return head2
        elif not head2:
            return head1
        # This is executed if both lists exist
        if head1.data<=head2.data:
            headmerged=head1
            head1=head1.next
        else:
            headmerged=head2
            head2=head2.next
        prevnode=headmerged
        while head1 and head2:
            if head1.data<=head2.data:
                prevnode.next=head1
                head1=head1.next
            else:
                prevnode.next=head2
                head2=head2.next
            prevnode=prevnode.next
        # One of the lists is exhausted
        # The remaining part of the other list is appended at end
        if not head1:
            prevnode.next=head2
        else:
            prevnode.next=head1
        return headmerged
    
  • + 0 comments

    Typescript is missing boilerplate function...

  • + 0 comments
    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        SinglyLinkedListNode dummy = new SinglyLinkedListNode(0);
        SinglyLinkedListNode curr = dummy;
    
        while (head1 != null && head2 != null) {
            if (head1.data > head2.data) {
                curr.next = head2;
                head2 = head2.next;
            }
            else {
                curr.next = head1;
                head1 = head1.next;
            }
            curr = curr.next;
        }
    
        // add left head2 nodes all
        if (head1 == null) curr.next = head2;
    
        // add left head1 nodes all
        if (head2 == null) curr.next = head1;
    
        return dummy.next;
    }
    
  • + 1 comment

    Recursive C++ Solution

    SinglyLinkedListNode* mergeLists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
        if (head1 == NULL) return head2;
        if (head2 == NULL) return head1; 
        
        if (head1->data < head2->data) {
            head1->next = mergeLists(head1->next, head2);
            return head1;
        }
        head2->next = mergeLists(head1, head2->next);
        return head2;
    }