Skip to content

Commit

Permalink
re-solve "21. Merge Two Sorted Lists"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 26, 2024
1 parent e6c9122 commit 447d34c
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/merge_two_sorted_lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,29 @@ class Solution:
def mergeTwoLists(
self, l1: ListNode | None, l2: ListNode | None
) -> ListNode | None:
dummy = ListNode()
tail = dummy
dummy = current = ListNode()

while l1 and l2:
if l1.val > l2.val:
tail.next = l2
l2 = l2.next
else:
tail.next = l1
if l1.val < l2.val:
node = ListNode(l1.val)
l1 = l1.next
tail = tail.next
else:
node = ListNode(l2.val)
l2 = l2.next

current.next = node
current = node

if l1:
tail.next = l1
while l1:
node = ListNode(l1.val)
current.next = node
current = node
l1 = l1.next

if l2:
tail.next = l2
while l2:
node = ListNode(l2.val)
current.next = node
current = node
l2 = l2.next

return dummy.next

0 comments on commit 447d34c

Please sign in to comment.