[英]Why does this code not return a reverse Linked List
Input = [1, 2, 3, 4, 5]
def reverseList(self, head):
prev = None
while head:
cur = head
cur.next = prev
head = head.next
prev = cur
return prev
I do not understand why the result above returns我不明白为什么上面的结果返回
Output = [1]
cur
is temporary variable and not affected by changes of the head variable (that is what I thought) cur
是临时变量,不受 head 变量变化的影响(这就是我的想法)
def reverseList(self, head):
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
returns the correct result, and I do not understand why.返回正确的结果,我不明白为什么。 It suggests that changes to head
also change the cur
variable, although it is changed AFTER cur is set to cur = head
它表明对head
的更改也会更改cur
变量,尽管它在 cur 设置为cur = head
之后更改
This is your example linked list:这是您的示例链接列表:
[1] -> [2] -> [3] -> [4] -> [5] [1] -> [2] -> [3] -> [4] -> [5]
Initially head
is pointing to [1]
and prev
is pointing to None
.最初head
指向[1]
而prev
指向None
。 Now let's execute your first code line by line.现在让我们逐行执行您的第一个代码。 You first set cur
to head
(eg, cur
is now pointing to [1]
), meaning from now on both head
and cur
is pointing to [1]
.您首先将cur
设置为head
(例如, cur
现在指向[1]
),这意味着从现在开始head
和cur
都指向[1]
。 Now, when you set cur.next = prev
you are actually setting [1].next = None
.现在,当您设置cur.next = prev
时,您实际上是在设置[1].next = None
。 So, the link between [1]
and [2]
is already broken and you loose all the other parts of the linked-list (eg, [2] -> [3] -> [4] -> [5]
) at this point.因此, [1]
和[2]
之间的链接已经断开,并且您在链接列表的所有其他部分(例如, [2] -> [3] -> [4] -> [5]
)这点。 Now when you do head = head.next
, this means you are doing [1] = [1].next
, where previously you set [1].next = None
.现在,当您执行head = head.next
时,这意味着您正在执行[1] = [1].next
,而之前您设置了[1].next = None
。 In the next run, the while loop
will terminate because the head become None
.在下一次运行中, while loop
将终止,因为 head 变为None
。
I would highly suggest you to do this type of simulation using pen and paper for the second code and you will understand the difference.我强烈建议您使用笔和纸对第二个代码进行此类模拟,您将了解其中的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.