Space
Open
From Fieldwork
Scales
Archive
Iterative.
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
# 1. Create a dummy node to act as the pre-head of the result.
# This avoids checking if the result head is None during the first iteration.
dummy = ListNode()
tail = dummy
# 2. Iterate while both lists have nodes remaining
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
# 3. Attach the remaining nodes.
# Since the lists are sorted, we just attach the remainder of the non-empty list.
# In Python, 'or' returns the first truthy value.
tail.next = list1 or list2
# 4. Return the next node after dummy (the actual head)
return dummy.nextPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode