最近比较懒,没怎么刷题,本来今天也不想刷题,但是想想自己当时说要每天一道题,不能食言,所以骨气勇气做了,在这边发帖子,督促自己做题的目的达到了。
class Solution(object):
def mergeTwoLists(self, l1, l2):
node = ListNode(0)
p = node
while l1 and l2:
if l1.val <= l2.val:
p.next = l1
p = p.next
l1 = l1.next
else:
p.next = l2
p = p.next
l2 = l2.next
if l1:
while l1:
p.next = l1
p = p.next
l1 = l1.next
elif l2:
while l2:
p.next = l2
p = p.next
l2 = l2.next
p = node.next
return p
还有一种简便的实现方式,原理和上面是一样的,只是代码能够简洁一些。
class Solution(object):
def mergeTwoLists(self, l1, l2):
head=ListNode(None)
temp=head
while l1 and l2:
if l1.val<=l2.val:
temp.next=l1
l1=l1.next
else:
temp.next=l2
l2=l2.next
temp=temp.next
temp.next=l1 if l1 else l2
return head.next