简体   繁体   English

向后添加和迭代链表以产生向后求和

[英]adding and iterating through linked list backwards to produce backwards sum

I am trying to add two linked lists backward such that they produce a third.我试图向后添加两个链表,以便它们产生第三个。 I am running into an issue in which I am missing the middle value in my expected out output.我遇到了一个问题,我在预期输出中缺少中间值。 I don't understand why this is happening.我不明白为什么会这样。

Example: 342 + 465 = 807(expected output)示例:342 + 465 = 807(预期输出)

input =输入 =

[2]->[4]->[3], [2]->[4]->[3],

[5]->[6]->[4] [5]->[6]->[4]

expected = [7]->[0]->[8]预期 = [7]->[0]->[8]

actual = [7]->[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

This might be what you are looking for.这可能就是您要寻找的。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM