![]() |
VOOZH | about |
Given 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->20Input: a: 1->1, b: 2->4
Output: 1->1->2->4
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:
👁 Merge-Two-Sorted-LinkedLists1
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
Merged Linked List is: 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
Merge Two Sorted Linked Lists with O(1) Auxiliary Space