gpt4 book ai didi

python - 在python中反转链表时无法访问链表的下一个节点

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:59 26 4
gpt4 key购买 nike

我对 python 有点陌生,我已经看到了解决链表问题的正确解决方案,但我想知道为什么我的解决方案不起作用。特别是,由于“new_list.head.next=prev”行,reverse 函数保留在下面代码的 while 循环中

class Node:
def __init__(self, value):
self.value = value
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, value):
if self.head is None:
self.head = Node(value)
return

node = self.head
while node.next:
node = node.next

node.next = Node(value)

def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next

def __repr__(self):
return str([v for v in self])

def reverse(linked_list):
new_list = LinkedList()
if linked_list is None:
return new_list
node = linked_list.head
new_list.head = node
while node.next:
prev = node
node = node.next
new_list.head = node
new_list.head.next = prev
return new_list

if __name__ == "__main__":
a = LinkedList()
b = [1,2,3,4,5]
for item in b:
a.append(item)
print a
c = reverse(a)
print c

最佳答案

如果您使用 Python3 标记您的问题,请确保它在 python 3 中运行。

原因是因为您混淆了点并创建了无限循环。打印 value,它可能会帮助您找到错误。我将使用这些值来指出问题。

    while node.next:
# First node that comes in value = 1
print(node.value) #
prev = node # prev = 1
node = node.next # node = 2
new_list.head = node # You are setting the head = 2 (i.e. head = node.next)
new_list.head.next = prev # You are setting next of head = 1 (i.e. head.next = node.next.next)
# however this also set node.next.next = 1
# So going into the next loop: node.value = 2 and node.next.value = 1

由于这种指针混淆,您永远在第一个和第二个节点之间循环。

关于python - 在python中反转链表时无法访问链表的下一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194314/

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