我正试图向后添加两个链表,以便它们生成第三个链表。我遇到了一个问题,在这个问题中,我错过了预期输出的中间值。我不明白为什么会发生这种事。
示例:342+465=807(预期输出(
输入=
[2] ->[4]->[3],
[5] ->[6]->[4]
预期=[7]->[0]->[8]
实际=[7]->[8]
carryOver = 0
current1 = l1
current2 = l2
result = None
resultC = None
while current1 is not None:
val = current1.val + current2.val+ carryOver
if val>= 10:
carryOver = val//10
else:
carryOver = 0
val = val%10
if result == None:
result = ListNode(val)
resultC = result
else:
resultC.next = ListNode(val)
current1 = current1.next
current2 = current2.next
if carryOver != 0:
resultC.next = ListNode(carryOver)
return result
这可能就是您想要的。
def add_list(l1,l2):
max_length=max(len(l1),len(l2))
l1,l2=[[0]]*(max_length-len(l1))+l1,[[0]]*(max_length-len(l2))+l2 # padding zeros
l1,l2=l1[::-1],l2[::-1]#temporary reversing of list
carry=0
d=[]
for x in zip(l1,l2):
tempsum=x[0][0]+x[1][0]+carry
carry=0
if tempsum>9:
carry,tempsum=tempsum//10,tempsum%10
d.append([tempsum])
if carry !=0:
d.append([carry])
return d[::-1]