算法-目录
题目来源: 2. 两数相加
![在这里插入图片描述](https://img-blog.csdnimg.cn/c888189504a5473d97f179b8104f9e28.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAWG5ZLXdlaQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/a6947c2cac644efebf79baa8514093d4.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAWG5ZLXdlaQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
递归
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
a=l1.val if l1 else 0
b=l2.val if l2 else 0
sum=ListNode((a+b)%10)
sum.next=self.addTwoNumbers(l1.next,l2.next)
if a+b>9:
sum.next=self.addTwoNumbers(sum.next,ListNode((a+b)//10))
return sum
迭代
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur=dummy=ListNode(0)
count=0
while l1 or l2 or count>0:
a=l1.val if l1 else 0
if l1 is not None:
l1=l1.next
b=l2.val if l2 else 0
if l2 is not None:
l2=l2.next
cur.next=ListNode((a+b+count)%10)
cur=cur.next
count=(a+b+count)//10
return dummy.next