链式A+B
题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
solution:
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Plus:
def plusAB(self, a, b):
carry = 0
pre = ListNode(0)
work = pre
while a and b:
temp = a.val + b.val + carry
if temp>9:
temp -= 10
carry = 1
else:
carry = 0
new = ListNode(temp)
work.next = new
work = work.next
a = a.next
b = b.next
while a:
temp = a.val + carry
if temp>9:
temp -= 10
carry = 1
else:
carry = 0
new = ListNode(temp)
work.next = new
work = work.next
a = a.next
while b:
temp = b.val + carry
if temp>9:
temp -= 10
carry = 1
else:
carry = 0
new = ListNode(temp)
work.next = new
work = work.next
b = b.next
if carry==1:
new = ListNode(1)
work.next = new
return pre.next