gpt4 book ai didi

python - Python中反转链表的方法

转载 作者:行者123 更新时间:2023-12-01 01:21:43 25 4
gpt4 key购买 nike

我尝试使用以下代码来反转链接列表,但出现无限循环错误。您能告诉我这种方法有什么问题吗?

def reverse(self):
temp = curr = self.head #curr refers to the next node
prev = None
while temp:
curr = temp.next #curr goes to the next node of temp
curr.next = temp #curr node points to its previous node temp
prev = temp #prev moves to the next node
temp = curr
#self.head.next = None
self.head = prev

最佳答案

您的方法存在逻辑错误。

在 while 循环的第一遍结束时:

  • curr (列表中的第二个元素)
  • curr.next (列表中的第一个元素)
  • temp = curr =(列表中的第二个元素)

在 while 循环的第二遍中。您希望使用 temp.next 到达第三个元素。这是错误的,因为:

  • temp.next = curr.next = (列表中的第一个元素)

让您在第一个和第二个元素之间无限循环,没有退出条件。

我将让您找出适当的解决方案。

(提示:temp 应分配给第一遍中的 ??? 元素)

关于python - Python中反转链表的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53755846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com