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
参考
添加回答
举报