GeeksforGeeks App
Open App
Browser
Continue

# Merge two sorted lists (in-place)

Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).

Examples:

Output : 4->5->6->7->8->9
Explanation: The output list is in sorted order.

Output : 1->2->3->4->5->7
Explanation: The output list is in sorted order.

There are different discussed different solutions in post below.

Method 1 (Recursive):

Approach: The recursive solution can be formed, given the linked lists are sorted.

2. Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.
3. The rest elements of both lists will appear after that.
4. Now run a recursive function with parameters, the next node of the smaller element, and the other head.
5. The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()
6. Handle some corner cases.
• If both the heads are NULL return null.
• If one head is null return the other.

Implementation:

## Javascript



Output

0 1 2 3 4 5

Complexity Analysis:

• Time complexity: O(n), Only one traversal of the linked lists are needed.
• Auxiliary Space: O(n), If the recursive stack space is taken into consideration.

Method 2 (Iterative):

Approach: This approach is very similar to the above recursive approach.

1. Traverse the list from start to end.
2. If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.
3. If the first list has reached end while traversing, point the next node to the head of second list.

Note: Compare both the lists where the list with a smaller head value is the first list.

Implementation:

## Javascript



Output

0  1  2  3  4  5

Complexity Analysis:

• Time complexity: O(n), As only one traversal of the linked lists is needed.
• Auxiliary Space: O(1), As there is no space required.

This article is contributed by Mandula Vikitha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up