法一:递归
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
法二:迭代
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res_head = ListNode(-2)
# 因为链表无头节点,所以自己创建头节点,其中 -2 无任何意义;头结点 -->next 指向第一个节点
res = res_head # 尾节点
while l1 and l2:
# 尾节点的 next 指向 “min(l1, l2)”
if l1.val < l2.val:
res.next = l1
l1 = l1.next
else:
res.next = l2
l2 = l2.next
res = res.next # 尾节点指针指向 “min(l1, l2)”,链表尾部添加节点成功
res.next = l1 if l1 is not None else l2
return res_head.next