question:
解法:用递归求解,这个时间复杂度不低
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 ==None:
return l2
if l2 == None:
return l1
# 创建一个新链表,头节点为res
res = ListNode()
# 再将头节点赋值给pre
pre = res
while l1 != None and l2 != None: #两个链表都有值的情况下
if l1.val > l2.val:
pre.next = l2
l2=l2.next
else:
pre.next = l1
l1=l1.next
pre = pre.next
if l1 == None: #如果有一个链表先遍历完,就直接把宁外一个链表剩下的值添加到新链表中
pre.next = l2
else:
pre.next = l1
return res.next