21. Merge Two Sorted Lists
# Easy
注意dummy node的用法
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# edge case
if l1 == None and l2 != None:
return l2
if l1 != None and l2 == None:
return l1
if l1 == None and l2 == None:
return l1
dummy = ListNode(0)
head = dummy
while l1 != None and l2 != None:
if l1.val <= l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
if l1 != None:
head.next = l1
elif l2 != None:
head.next = l2
return dummy.next
Last updated
Was this helpful?