Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2971 from coopers/0021
Browse files Browse the repository at this point in the history
Update 0021-merge-two-sorted-lists.py
  • Loading branch information
sujal-goswami committed Sep 4, 2023
2 parents 8578dd8 + 3e8f1a2 commit c581ec1
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions python/0021-merge-two-sorted-lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,32 @@
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

# Iterative
class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
dummy = ListNode()
tail = dummy
dummy = node = ListNode()

while list1 and list2:
if list1.val < list2.val:
tail.next = list1
node.next = list1
list1 = list1.next
else:
tail.next = list2
node.next = list2
list2 = list2.next
tail = tail.next
node = node.next

if list1:
tail.next = list1
elif list2:
tail.next = list2
node.next = list1 or list2

return dummy.next

# Recursive
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
lil, big = (list1, list2) if list1.val < list2.val else (list2, list1)
lil.next = self.mergeTwoLists(lil.next, big)
return lil

0 comments on commit c581ec1

Please sign in to comment.