思路:
先倒置,再求和,将结果倒置返回。
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# step1:先反转l1和l2
link1 = None
while l1:
temp = l1.next
l1.next = link1
link1 = l1
l1 = temp
link2 = None
while l2:
temp = l2.next
l2.next = link2
link2 = l2
l2 = temp
# step2:两数相加
pre = node = ListNode(0)
# 进位
extra = 0
while link1 and link2:
node.next = ListNode(0)
# 求当前位的总和
sum = link1.val + link2.val + extra
# 计算当前位的值
node.next.val = sum % 10
# 计算进位
extra = int(sum / 10)
# 顺移
node = node.next
link1 = link1.next
link2 = link2.next
res = link1 or link2
while res:
node.next = ListNode(0)
sum = res.val + extra
node.next.val = sum % 10
extra = int(sum / 10)
node = node.next
res = res.next
if extra:
node.next = ListNode(0)
node.next.val = extra
# step3:反转结果链表
pre = pre.next
ans = None
while pre:
temp = pre.next
pre.next = ans
ans = pre
pre = temp
return ans