Merge Two Sorted Lists
- 1 min read
- LC-Easy
- Blind75
- Recursion
- Linked List
Approach 1: Iterative
Kinda like merge sort. Nothing to explain really. It's kinda easy.
def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = cur = ListNode()
while list1 and list2:
if list1.val <= list2.val:
cur.next = ListNode(list1.val)
list1 = list1.next
else:
cur.next = ListNode(list2.val)
list2 = list2.next
cur = cur.next
if list1: cur.next = list1
else: cur.next = list2
return head.next
Approach 2: Recursive
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2