2 回答

TA貢獻1848條經驗 獲得超6個贊
問題在于您的 newLL 變量以及您如何將數字附加到鏈表中。您已經創建了該列表的頭部,并且最多使用 newLL.next 上升到第二個值,但是您沒有遍歷列表以添加更多值。這是一個可能的解決方案:
def addTwoNumbers(l1, l2):
Rhead1 = reverseLL(l1) # 3 -> 4 -> 2
Rhead2 = reverseLL(l2) # 4 -> 6 -> 5
node1 = Rhead1
node2 = Rhead2
carry = 0
newLL = None
temp = None
while node1 and node2:
arith = node1.data + node2.data + carry
# print('node1: {0} + node2: {1} + carry: {2} = arith: {3}'.format(node1.data,
#node2.data, carry, arith))
carry = 0
if arith >= 10: carry, arith = divmod(arith, 10)
if newLL:
temp.next = Node(arith)
temp = temp.next
else:
newLL = Node(arith)
temp = newLL
node1, node2 = node1.next, node2.next
return newLL

TA貢獻1804條經驗 獲得超2個贊
干得好使用unittest和carry, arith = divmod(arith, 10)!
不確定你的錯誤,但我們可以使用哨兵節點并更容易地解決問題。
這會過去:
class Solution:
def addTwoNumbers(self, a, b):
carry = 0
sentinel = p = ListNode(0)
while a or b or carry:
if a:
carry, a = carry + a.val, a.next
if b:
carry, b = carry + b.val, b.next
carry, val = carry // 10, carry % 10
p.next = p = ListNode(val)
return sentinel.next
參考
添加回答
舉報