输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 考虑2种情况
# 1、有进位
# 2、2个长度不同时
result = ListNode(0);
p = result
i = 0 #进位
while l1 or l2 or i:
i += (l1.val if l1 else 0) + (l2.val if l2 else 0)
p.next = ListNode(i % 10)
p = p.next
i = i // 10
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return result.next