The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A current pointer tracks the last node of the merged list. We compare the nodes from both lists and append the smaller node to the merged list. Once one list is fully traversed, the remaining nodes from the other list are appended. The merged list is returned starting from the node after the dummy node.
Below is the working of above approach:
Below is the implementation of above approach:
Output
2 3 5 10 15 20 40
Time Complexity: O(n + m), where n and m are the length of head1 and head2 respectively. Auxiliary Space: O(1)