给出两个非空链表用来表示两个非负整数。其中,它们各自的位数按照逆序方式存储,并且每个节点只能存储一位数字。如’1 -> 2 -> 3’表示’321’。以链表形式返回两数之和。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def addTwoNumbers(l1, l2):
carry, result = 0, ListNode(0)
temp = result
while l1 or l2:
x1 = l1.val if l1 else 0
x2 = l2.val if l2 else 0
s = x1 + x2 + carry
carry = s // 10
temp.next = ListNode(s % 10)
temp = temp.next
if l1 is not None and l2 is not None:
l1 = l1.next
l2 = l2.next
else:
break
if carry != 0: # 最后一个节点相加有进位,如5 + 5 = 10
temp.next = ListNode(carry)
return result.next