Aniket Vaishnav

Posted on

# Merge two sorted linked lists

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

Input: Two lists of N and M nodes are provided
However, number of nodes are not the game changing factor, one can execute the operation even despite measuring the length.

### Approach

Both the lists are sorted, it's a good idea to check either of the 1st node in the list which of them is smaller, consider that advance the pointer corresponding to the smaller node.

An example demonstrated in the following image:

In the end, when there is a left out nodes, we simply just append the nodes to the result list.

For the above approach,
Time Complexity: O(min(n, m))
i.e., The Smallest linked list travel amount.
Space Complexity: O(1)
i.e., No such extra auxiliary space required proportional to input.

Few implementations for the same can be found below.

### 1. Java implementation.

``````/*
head pointer input could be NULL as well for empty list
Node is defined as
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
*/

{
Node res = new Node(-1);
Node itr = res;
} else {
}
itr = itr.next;
}
return res.next;
}

void fillRest(Node head, Node itr) {
}
}

``````

### 2. JavaScript / Node.js implementation.

``````
class Solution {
}

{
let res = new Node(-1);
let itr = res;

let getMin = () => {
let min;
} else {
}
return min;
};

itr.next = getMin();
itr = itr.next;
}
return res.next;
}
}

``````

### 3. C++ implementation.

``````
struct Node {
int data;
struct Node *next;

Node(int x) {
data = x;
next = NULL;
}
};
*/

//Function to merge two sorted linked list.
{
// code here
Node res(-1);
Node *itr = &res;

auto fillRest = [] (Node* head, Node* itr) {
};

} else {