Skip to content

Update 0021-merge-two-sorted-lists.py #2971

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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