20. Merge Two Sorted Linked Lists
The problem can be found at the following link: Problem Link
Problem Description
Given the heads of two sorted linked lists, the task is to merge the two lists into a single sorted linked list and return the head of the merged list.
Examples
Example 1:
Input:
head1 = 5 -> 10 -> 15 -> 40
head2 = 2 -> 3 -> 20
Output:
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40
Explaination:
Example 2:
Input:
head1 = 1 -> 1
head2 = 2 -> 4
Output:
1 -> 1 -> 2 -> 4
Constraints:
1 <= no. of nodes<= $10^3$
$
0 <= node->data <= 10^5$
My Approach
Iterative Approach:
Create a dummy node to simplify the merging process and maintain a pointer
tailstarting at the dummy node.Traverse both linked lists using two pointers,
head1andhead2.Compare the data of the current nodes from both lists.
Attach the node with the smaller value to
tailand move the pointer of the respective list.
Once one of the lists is completely traversed, attach the remaining nodes of the other list to
tail.Return the merged list starting from
dummy.next.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n + m), where
nandmare the lengths of the two linked lists. Each node is visited exactly once.Expected Auxiliary Space Complexity: O(1), as no additional space is used except for a few variables.
Code (C)
Code (C++)
Iterative Approach (Tail Insertion Merge)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated