![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f8eec62cc5807414dd8c973db9084159.png)
方法:链表反转后相加
class Solution:
def reverse(self, head):
pre = head
cur = head.next
pre.next = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l1 = self.reverse(l1)
l2 = self.reverse(l2)
h = ListNode((l1.val + l2.val) % 10)
flag = (l1.val + l2.val) // 10
p = h
l1 = l1.next
l2 = l2.next
while l1 or l2 or flag:
if l1 and l2:
node = ListNode((l1.val + l2.val + flag) % 10)
flag = (l1.val + l2.val + flag) // 10
l1 = l1.next
l2 = l2.next
elif l1:
node = ListNode((l1.val + flag) % 10)
flag = (l1.val + flag) // 10
l1 = l1.next
elif l2:
node = ListNode((l2.val + flag) % 10)
flag = (l2.val + flag) // 10
l2 = l2.next
elif flag:
node = ListNode(flag)
flag = 0
p.next = node
p = node
return self.reverse(h)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c457f7e9f03878cbc5618b4040071e78.png)