# Merge two sorted linked lists

• Difficulty Level : Medium
• Last Updated : 25 Jan, 2023

AuxiliaryGiven two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the lists (in place) and return the head of the merged list.

Examples:

Input: a: 5->10->15, b: 2->3->20
Output: 2->3->5->10->15->20

Input: a: 1->1, b: 2->4
Output: 1->1->2->4

## Brute Force Way:

The Approach:

In this Approach we use a vector of (n+m) size where n and m are length respective linked list and then store all the element in vector and then we sort the vector and make new linked list it will be our answer.

## C++

 #include using namespace std;    /* Link list Node */ struct Node {     int key;     struct Node* next; };   Node* newNode(int key){     Node* temp = new Node;     temp->key = key;     temp->next = NULL;     return temp; } int main() {     /* Let us create two sorted linked lists to test        the above functions. Created lists shall be          a: 5->10->15->40          b: 2->3->20  */     Node* a = newNode(5);     a->next = newNode(10);     a->next->next = newNode(15);     a->next->next->next = newNode(40);        Node* b = newNode(2);     b->next = newNode(3);     b->next->next = newNode(20);    vectorv;     while(a!=NULL){      v.push_back(a->key);      a=a->next;     }      while(b!=NULL){      v.push_back(b->key);      b=b->next;     }      sort(v.begin(),v.end());      Node* result= newNode(-1);      Node* temp=result;      for(int i=0;inext=newNode(v[i]);       result=result->next;      }      temp=temp->next;      cout<<"Resultant Merge Linked List Is :"<key<<" ";        temp=temp->next;      }     return 0; }

## Javascript

 // JavaScript program for the above approach // Link List node class Node{     constructor(key){         this.key = key;         this.next = null;     } }   function newNode(key){     let temp = new Node(key);     return temp; }   // driver code // let us create two sorted linked lists to test the above // function. Created lists shall be // a: 5->10->15->40 // b: 2->3->20   let a = newNode(5); a.next = newNode(10); a.next.next = newNode(15); a.next.next.next = newNode(40);   let b = newNode(2); b.next = newNode(3); b.next.next = newNode(20);   let v = []; while(a != null){     v.push(a.key);     a = a.next; }   while(b != null){     v.push(b.key);     b = b.next; }   v.sort(function(a, b){return a - b}); let result = newNode(-1); let temp = result; for(let i = 0; i

Output

Resultant Merge Linked List Is :
2 3 5 10 15 20 40

Complexity Analysis:

Time Complexity:O((n+m)*(n+m)log(n+m)),(n+m)for traversing linked lists and (n+m)log(n+m) for sorting vector.
Auxiliary Space: O(n+m),for vector.

## Merge two sorted linked lists using Dummy Nodes:

The idea is to use 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.

Follow the below illustration for a better understanding:

Illustration:

Follow the steps below to solve the problem:

• First, make a dummy node for the new merged linked list
• Now make two pointers, one will point to list1 and another will point to list2.
• Now traverse the lists till one of them gets exhausted.
• If the value of the node pointing to either list is smaller than another pointer, add that node to our merged list and increment that pointer.

Below is the implementation of the above approach:

## Javascript



Output

2 3 5 10 15 20

Time Complexity: O(N + M), where N and M are the size of list1 and list2 respectively
Auxiliary Space: O(1)

## Merge two sorted linked lists using Recursion:

The idea is to move ahead with node in the recursion whose node value is lesser. When any of the node reach the end then append the rest of the linked List.

Follow the steps below to solve the problem:

• Make a function where two pointers pointing to the linked list will be passed.
• Now, check which value is less from both the current nodes
• The one with less value makes a recursion call by moving ahead with that pointer and simultaneously append that recursion call with the node
• Also put two base cases to check whether one of the linked lists will reach the NULL, then append the rest of the linked list.

Below is the implementation of the above approach.

## Javascript



Output

2 3 5 10 15 20

Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space

## Merge two sorted linked lists by 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.

Follow the steps below to solve the problem:

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

Below is the implementation of the above solution.

## Javascript

"); printList(res);   // This code is contributed by lokeshmvs21.

Output

2 3 5 10 15 20 40

Time Complexity: O(M+N) where M and N are the lengths of the two lists to be merged.
Auxiliary Space: O(M+N)

This method is contributed by Mehul Mathur(mathurmehul01)

Please refer below post for simpler implementations :
Merge two sorted lists (in-place)
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.

My Personal Notes arrow_drop_up
Related Articles