# 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(0) current = l3 carry = 0 while l1 or l2: # 1,1 | None,1 | 1,None # Pad 0 if None if l1 is None: l1v = 0 else: l1v = l1.val if l2 is None: l2v = 0 else: l2v = l2.val # Sum tmp = l1v + l2v + carry if tmp >= 10: x = tmp%10 carry = int(tmp/10) else: x = tmp carry = 0 # 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 != 0: current.next = ListNode(carry) return l3.next node1=ListNode(1) node2=ListNode(2) node3=ListNode(3) node1.next=node2 node2.next=node3 node4=ListNode(4) node5=ListNode(5) node6=ListNode(6) 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)
输出
5 7 9