给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
# 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):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1i = []
while l1:
l1i.append(l1)
l1 = l1.next
#l1i.reverse()
l2i = []
while l2:
l2i.append(l2)
l2 = l2.next
#l2i.reverse()
rt = []
is1 = True if len(l1i)>len(l2i) else False
maxl = len(l1i) if len(l1i)>len(l2i) else len(l2i)
minl = len(l1i) if len(l1i)<len(l2i) else len(l2i)
for i in xrange(maxl):
if i < minl:
if i+1 == len(rt) and rt[i]:
if rt[i]+l1i[i].val + l2i[i].val > 9:
rt[i]=(rt[i]+l1i[i].val+l2i[i].val)%10
rt.append(1)
else:
rt[i]=rt[i]+l1i[i].val+l2i[i].val
else:
if l1i[i].val + l2i[i].val > 9:
rt.append((l1i[i].val+l2i[i].val)%10)
rt.append(1)
else:
rt.append(l1i[i].val+l2i[i].val)
else:
if i+1 == len(rt) and rt[i]:
t = l1i[i].val if is1 else l2i[i].val
if rt[i]+ t > 9:
rt[i]=(rt[i]+ t)%10
rt.append(1)
else:
rt[i]=rt[i]+ t
else:
rt.append(l1i[i].val if is1 else l2i[i].val)
#print rt
#rt.reverse()
print rt
rtl = [ListNode(x) for x in rt]
for i,x in enumerate(rtl):
if i+1 < len(rtl):
x.next = rtl[i+1]
else:
x.next = None
return rtl[0]