链表1 合并两个有序链表
1、方法1,迭代法
(1)链表数据,注意要有哨兵节点
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(None)
l = res
while l1 and l2:
if l1.val<l2.val:
l.next=l1
l1=l1.next
else:
l.next=l2
l2=l2.next
l = l.next
if l1:
l.next=l1
else:
l.next=l2
return res.next
2、方法2,递归法,注意最后返回非空的那个链表
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val<l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
return l1 or l2
比较好的参考资料:
1、解法和链表数据 https://www.pythonf.cn/read/79182