我编写了这段代码,以添加两个数字存储为Leetcode上的问题的链接列表。我得到的输出表明我的变量没有在while循环中更新,但是我不明白为什么。我想念什么?
# Definition for singly-linked list.
#class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carrybit = 0
output = ListNode(0)
iteration = 0
while l1.next != None or l2.next != None:
temp = ListNode((l1.val + l2.val + carrybit)%10)
if l1.val + l2.val + carrybit > 9:
carrybit = 1
else:
carrybit = 0
temp2 = output.next
while temp2 != None:
temp2 = temp2.next
temp2 = temp
l1 = l1.next
l2 = l2.next
return output
答案 0 :(得分:0)
您正在为本地target_include_directories(
${ELF}
PRIVATE
"source"
"source/target/arm/stm32f1/CMSIS/Device/ST/STM32F1xx/Include"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/include/c++/7.3.1"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/include/c++/7.3.1/arm-none-eabi"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/include/c++/7.3.1/backward"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/include"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/include-fixed"
"${tools}\\bin\\../lib/gcc/arm-none-eabi/7.3.1/../../../../arm-none-eabi/include"
)
变量分配值。这样做只会更改temp2
,temp2
或先前的output.next
不会被修改。
要更改它,您实际上需要分配给temp2.next
。
答案 1 :(得分:0)
此代码绝对无效:
temp2 = output.next
while temp2 != None:
temp2 = temp2.next
temp2 = temp
更新temp2
的值,直到达到None
,然后将其替换为temp
。之后,将不再使用temp2
,也不会使用temp
。都使用不依赖于此操作结果的新值来重新分配它们。
由于temp
被分配了一个新的ListNode
,而该ListNode
没有链接到任何东西并且从未更改,因此carrybit
将超出范围并消失。
发生的唯一另一件事是分配了ListNode
,该分配仅在将被丢弃的def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
output = None
lastNode = None
carry = 0
while not (l1 is None and l2 is None):
if l1 : carry,l1 = l1.val+carry,l1.next
if l2 : carry,l2 = l2.val+carry,l2.next
nextNode = ListNode(carry%10)
carry = carry // 10
if output: lastNode.next = nextNode
else : output = nextNode
lastNode = nextNode
if carry:
lastNode.next = ListNode(carry%10)
return output
中使用。
整个while循环最终什么都不做。
我建议使用一种不太复杂的方法:
» docker build --label $(echo -n 'key="name value"') .
"docker build" requires exactly 1 argument.
See 'docker build --help'.
Usage: docker build [OPTIONS] PATH | URL | -
Build an image from a Dockerfile