题目:将两个有序链表合并为一个新的有序链表并返回
法:和合并两个有序数组一样的思路,都是用两个指针p与q分别指向两个链表的头节点,注意每次不让链表断掉即可
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None:return l2
if l2==None:return l1
p,q=l1,l2
res=ListNode(0)
tmp=res
while p!=None and q!=None:
if p.val<=q.val:
tmp.next=p
p=p.next
else:
tmp.next=q
q=q.next
tmp=tmp.next
if p:tmp.next=p
elif q:tmp.next=q
return res.next