When dealing with linked lists, merging two sorted lists is a common task. In this blog post, we'll walk through a Python solution to merge two sorted linked lists into one sorted list. We'll provide detailed steps and explanations along with the code. Additionally, we'll discuss the time and space complexity of our solution.
Let's dive into the problem and its solution.
Problem Statement
You are given the heads of two sorted linked lists, list1
and list2
. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Solution Approach
To merge two sorted linked lists efficiently, we'll utilize a common algorithmic approach. We'll maintain two pointers, one for each input list (list1
and list2
). We'll compare the values of the nodes pointed by these pointers and keep adding the smaller one to our merged list. We'll continue this process until we reach the end of either list. Finally, we'll append the remaining elements (if any) from the non-empty list to the end of our merged list.
Python Implementation
Let's implement the solution step by step:
pythonCopy code# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: # Initialize a dummy node and a tail pointer dummy = ListNode() tail = dummy # Iterate through both lists until one of them becomes empty while list1 and list2: if list1.val < list2.val: tail.next = list1 list1 = list1.next else: tail.next = list2 list2 = list2.next tail = tail.next # Append the remaining elements from non-empty list if list1: tail.next = list1if list2: tail.next = list2 # Return the head of the merged list return dummy.next
Understanding the Code
- We define a
ListNode
class representing each node of the linked list. - In the
mergeTwoLists
function, we create a dummy node to simplify the code. This dummy node will always point to the head of our merged list. - We maintain a
tail
pointer to keep track of the last node added to our merged list. This helps in appending new nodes efficiently. - We iterate through both lists simultaneously, comparing their values and adding the smaller one to our merged list until one of the lists becomes empty.
- Finally, we append any remaining nodes from the non-empty list to the end of our merged list.
- The function returns the head of the merged list.
Time and Space Complexity
- Time Complexity: We traverse each node of both input lists exactly once, so the time complexity is O(n + m), where n and m are the lengths of
list1
andlist2
, respectively. - Space Complexity: We only use a constant amount of extra space for pointers and variables. Hence, the space complexity is O(1).
Conclusion
In this blog post, we discussed an efficient Python solution to merge two sorted linked lists. We walked through the implementation step by step and analyzed the time and space complexity of our solution. This approach provides an optimal way to merge two sorted linked lists, making it suitable for large inputs.
I hope this blog post helps you understand the problem and its solution effectively. Happy coding! 🚀