对于链表中的每个节点依此相加,同时记录节点相加后的进位情况
主要有以下两种情况
1.链表一样长的情况
2.链表不一样长的情况,需要处理计算完成后剩余节点
我采用产生一个新的链表依此记录相应节点的结果。
欢迎一起交流
def listAdd(a,b):
if a is None or a.next is None:
return
if b is None or b.next is None:
return
sum = 0 #两个节点相加的和
p1 = a.next
p2 = b.next
c = 0 #进位数
res = Node()
res.next = None
p = res#结果链表的末尾位置引用,用于结果插入
while p1 is not None and p2 is not None:
cur = Node()
cur.next = None
sum = p1.x+p2.x+c
cur.x = sum%10
c = sum/10
p.next = cur
p = cur
p1 = p1.next
p2 = p2.next
if p1 is None:#p2链表比p1长的时候
while p2 is not None:
cur = Node()
cur.next = None
sum = p2.x + c
cur.x = sum%10
c = sum/10
p.next = cur
p = cur
p2 = p2.next
if p2 is None:
while p1 is not None:
cur = Node()
cur.next = None
sum = p1.x + c
cur.x = sum%10
c = sum/10
p.next = cur
p = cur
p1 = p1.next
if c == 1: #若计算完成还有进位
cur = Node()
cur.next = None
cur.x = 1
p.next = cur
return res
网友评论