• Difficulty Level : Medium
• Last Updated : 17 Jan, 2022

Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists.

For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20.

There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally, there’s the problem of starting the result list empty, and building it up while going through ‘a’ and ‘b’.

Method 1 (Using Dummy Nodes)
The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.

The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to the tail. When

We are done, the result is in dummy.next.

The below image is a dry run of the above approach: Below is the implementation of the above approach:

Javascript



Output :

2 3 5 10 15 20

Method 2 (Using Local References)
This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used (see Section 1 for details).

C++14

 Node* SortedMerge(Node* a, Node* b){Node* result = NULL;     /* point to the last result pointer */Node** lastPtrRef = &result;     while(1){    if (a == NULL)    {    *lastPtrRef = b;    break;    }    else if (b==NULL)    {    *lastPtrRef = a;    break;    }    if(a->data <= b->data)    {    MoveNode(lastPtrRef, &a);    }    else    {    MoveNode(lastPtrRef, &b);    }         /* tricky: advance to point to the next ".next" field */    lastPtrRef = &((*lastPtrRef)->next);}return(result);} //This code is contributed by rathbhupendra

C

 struct Node* SortedMerge(struct Node* a, struct Node* b){  struct Node* result = NULL;     /* point to the last result pointer */  struct Node** lastPtrRef = &result;     while(1)  {    if (a == NULL)    {      *lastPtrRef = b;       break;    }    else if (b==NULL)    {       *lastPtrRef = a;       break;    }    if(a->data <= b->data)    {      MoveNode(lastPtrRef, &a);    }    else    {      MoveNode(lastPtrRef, &b);    }       /* tricky: advance to point to the next ".next" field */    lastPtrRef = &((*lastPtrRef)->next);  }  return(result);}

Java

 Node SortedMerge(Node a, Node b){Node result = null;     /* point to the last result pointer */Node lastPtrRef = result;     while(1){    if (a == null)    {    lastPtrRef = b;    break;    }    else if (b==null)    {    lastPtrRef = a;    break;    }    if(a.data <= b.data)    {    MoveNode(lastPtrRef, a);    }    else    {    MoveNode(lastPtrRef, b);    }         /* tricky: advance to point to the next ".next" field */    lastPtrRef = ((lastPtrRef).next);}return(result);}  // This code contributed by umadevi9616

Python3

 def SortedMerge( a,  b):    result = None;             ''' point to the last result pointer '''    lastPtrRef = result;             while(1):        if (a == None):            lastPtrRef = b;            break;        elif(b == None):            lastPtrRef = a;            break;        if(a.data <= b.data):            MoveNode(lastPtrRef, a);        else:            MoveNode(lastPtrRef, b);         ''' tricky: advance to poto the next ".next" field '''        lastPtrRef = ((lastPtrRef).next);    return(result);    # This code is contributed by umadevi9616

C#

 Node SortedMerge(Node a, Node b){    Node result = null;             // Point to the last result pointer    Node lastPtrRef = result;             while(1)    {        if (a == null)        {            lastPtrRef = b;            break;        }        else if (b == null)        {            lastPtrRef = a;            break;        }        if (a.data <= b.data)        {            MoveNode(lastPtrRef, a);        }        else        {            MoveNode(lastPtrRef, b);        }                 // tricky: advance to point to        // the next ".next" field        lastPtrRef = ((lastPtrRef).next);    }    return(result);} // This code is contributed by gauravrajput1

Javascript



Method 3 (Using Recursion)
Merge is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn’t want to use the recursive version for production code, however, because it will use stack space which is proportional to the length of the lists.

C++

 Node* SortedMerge(Node* a, Node* b){    Node* result = NULL;         /* Base cases */    if (a == NULL)        return(b);    else if (b == NULL)        return(a);         /* Pick either a or b, and recur */    if (a->data <= b->data)    {        result = a;        result->next = SortedMerge(a->next, b);    }    else    {        result = b;        result->next = SortedMerge(a, b->next);    }    return(result);} // This code is contributed by rathbhupendra

C

 struct Node* SortedMerge(struct Node* a, struct Node* b){  struct Node* result = NULL;   /* Base cases */  if (a == NULL)     return(b);  else if (b==NULL)     return(a);   /* Pick either a or b, and recur */  if (a->data <= b->data)  {     result = a;     result->next = SortedMerge(a->next, b);  }  else  {     result = b;     result->next = SortedMerge(a, b->next);  }  return(result);}

Java

 class GFG{    public Node SortedMerge(Node A, Node B)    {             if(A == null) return B;        if(B == null) return A;                 if(A.data < B.data)        {            A.next = SortedMerge(A.next, B);            return A;        }        else        {            B.next = SortedMerge(A, B.next);            return B;        }             }} // This code is contributed by Tuhin Das

C#

 using System; class GFG{ public Node sortedMerge(Node A, Node B){         // Base cases    if (A == null)        return B;    if (B == null)        return A;             // Pick either a or b, and recur    if (A.data < B.data)    {        A.next = sortedMerge(A.next, B);        return A;    }    else    {        B.next = sortedMerge(A, B.next);        return B;    }}} // This code is contributed by hunter2000

Javascript



Time Complexity:  Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged.

Method 4 (Reversing The Lists)

This idea involves first reversing both the given lists and after reversing, traversing both the lists till the end and then comparing the nodes of both the lists and inserting the node with a larger value at the beginning of the result list. And in this way we will get the resulting list in increasing order.

1) Initialize result list as empty: head = NULL.
2) Let 'a' and 'b' be the heads of first and second list respectively.
3) Reverse both the lists.
4) While (a != NULL and b != NULL)
a) Find the larger of two (Current 'a' and 'b')
b) Insert the larger value of node at the front of result list.
c) Move ahead in the list of larger node.
5) If 'b' becomes NULL before 'a', insert all nodes of 'a'
into result list at the beginning.
6) If 'a' becomes NULL before 'b', insert all nodes of 'b'
into result list at the beginning.

Below is the implementation of above solution.

C#

Output:

List A before merge:
5 10 15 40
List B before merge:
2 3 20
2 3 5 10 15 20 40

Time Complexity:  Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged.

This method is contributed by Mehul Mathur(mathurmehul01)

This idea is similar to this post.

Please refer below post for simpler implementations :
Merge two sorted lists (in-place)