# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2):
l3 = ListNode()
current = l3
carry =
while l1 or l2: # , | None, | ,None
# Pad if None
if l1 is None:
l1v =
else:
l1v = l1.val
if l2 is None:
l2v =
else:
l2v = l2.val
# Sum
tmp = l1v + l2v + carry
if tmp >= :
x = tmp%
carry = int(tmp/)
else:
x = tmp
carry =
# Assign value
current.next = ListNode(x)
current = current.next
if l1 is not None:
l1 = l1.next
if l2 is not None:
l2 = l2.next
if carry != :
current.next = ListNode(carry)
return l3.next node1=ListNode()
node2=ListNode()
node3=ListNode() node1.next=node2
node2.next=node3 node4=ListNode()
node5=ListNode()
node6=ListNode() node4.next=node5
node5.next=node6 x=Solution()
print(x.addTwoNumbers(node1,node4).val)
print(x.addTwoNumbers(node1,node4).next.val)
print(x.addTwoNumbers(node1,node4).next.next.val)
输出