两数相加
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
输入:(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, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
tmp = ListNode(0)
res = tmp
c = 0
while l1 or l2:
sum = 0
if l1:
sum = l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
sum += c
num = sum % 10
c = sum // 10
res.next = ListNode(num)
res = res.next
if c:
res.next = ListNode(c)
res = tmp.next
del tmp
return res