我在这里看到了很多类似的问题,但没有一个涉及我想知道的内容。让我们举个例子。
我想从数组创建一个链接列表。忽略所有的样板文件,让我们进入这个问题的核心。
arr = [1, 2, 3, 4, 5]
tail = head = None # this is the problematic line
for item in arr:
tail = Node(val=item, next=None)
tail = tail.next
return head
不用说,这是行不通的。无论 tail 指向什么,Head 始终指向 None。
我尝试过的其他一些事情:
head = tail = [] # head will point to the empty list after finishing
head = tail = any_other_singleton # does not work
我知道为什么会发生这种情况。这是因为我正在重新分配 tail 以指向节点。但我想在“head”中保留对喜欢列表的头部的引用。我怎样才能做到这一点?在其他编程语言中,这是微不足道的,但在 python 中,您必须在声明时为变量赋值,这给我带来了问题。
最佳答案
单独处理第一项即可。
arr = [1, 2, 3, 4, 5]
head = tail = Node(val=arr[0], next=None)
for item in arr[1:]:
tail.next = Node(val=item, next=none)
tail = tail.next
return head
关于python - 在Python中初始化两个变量以指向相同的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69122961/