Merge Two Sorted Linked Lists
Problem Statement
Given the heads of two sorted linked lists, merge them into one sorted linked list and return the head of the merged list.
Example
Input
List1
1 -> 2 -> 4
List2
1 -> 3 -> 4
Output
1 -> 1 -> 2 -> 3 -> 4 -> 4
Approach Iterative Method
Compare nodes from both lists and build a new sorted list.
Steps
1 Create a dummy node to store result
2 Compare values of both lists
3 Attach smaller node to result
4 Move pointer of that list
5 Repeat until one list becomes empty
6 Attach remaining nodes
Code
```python id="mll1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
dummy = ListNode(0)
tail = dummy
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
if l2:
tail.next = l2
return dummy.next
---
## Approach Recursive Method
---
### Code
```python id="mll2"
def mergeTwoLists(l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = mergeTwoLists(l1, l2.next)
return l2
Explanation
The iterative method builds the merged list step by step using a dummy node. The recursive method compares nodes and builds the list during function calls.
Expected Output
Input
1 -> 2 -> 4
1 -> 3 -> 4
Output
1 -> 1 -> 2 -> 3 -> 4 -> 4
Conclusion
Merging two sorted linked lists is a basic and important problem. It helps in understanding linked list traversal and pointer manipulation.
Practice both iterative and recursive methods to improve your coding skills.
Top comments (0)