You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解析:把两个逆序存储的两个数相加
完整代码:
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
def setVal(self,a,b):
t=self
t.next=ListNode(a)
t=t.next
t.next=ListNode(b)
return self
class Solution(object):
def addTwoNumbers(self,l1,l2):
h=ListNode(0)
value=0
p=h
while l1 or l2:
sum=value
if l1:
sum,l1=l1.val+sum,l1.next
if l2:
sum,l2=l2.val+sum,l2.next
p.next=ListNode(sum%10)
value=sum/10
p=p.next
p.next=ListNode(value) if value else None
return h.next
def start():
l1=ListNode(2)
l1.setVal(4,3)
l2=ListNode(5)
l2.setVal(6,4)
add=Solution()
l3=add.addTwoNumbers(l1,l2)
while l3:
print l3.val,
l3=l3.next