How to merge 2 Sorted Linked list in C++?
1 min readJan 3, 2021
Example:
L1: 1 →4 →6 →8 →10
L2: 5→7 →9 →11 →12
Result: 1 →4 →5 →6 →7 →9 →10 →11 →12
Pseudo Code:
while A not empty or B not empty:
if first element of A < first element of B:
remove first element from A
insert element into C
end if
else:
remove first element from B
insert element into C
end while
Recursive Method:
- Compare the head of both lists.
- Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.
- The rest elements of both lists will appear after that.
- Now run a recursive function with parameters, the next node of the smaller element and the other head.
- 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()
- Handle some corner cases.
- If both the heads are NULL return null.
- If one head is null return the other.