class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class List:
def init_list(self, data):
if len(data) == 0:
return None
else:
head = ListNode(data[0])
tail = head
for i in data[1:]:
node = ListNode(i)
tail.next = node
tail = node
return head
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
p = res
carry = 0
while l1 or l2 or carry:
t1 = l1.val if l1 else 0
t2 = l2.val if l2 else 0
carry, b = divmod((t1 + t2 + carry), 10)
p.next = ListNode(b)
p = p.next
l1 = l1.next if l1 else l1
l2 = l2.next if l2 else l2
return res.next
a = [2, 4, 3]
l1 = List().init_list(a)
b = [5, 6, 4]
l2 = List().init_list(b)
aa = Solution().addTwoNumbers(l1, l2)
print(aa.val)
print(aa.next.val)
print(aa.next.next.val)
结果
7
0
8