【发布时间】:2020-11-25 06:19:15
【问题描述】:
所以我有这个代码
class Node():
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
self.length = 0
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
self.length += 1
def print_list(self):
if self.head == None:
print('Empty')
else:
currentNode = self.head
while currentNode != None:
print(currentNode.data, end = ' ')
currentNode = currentNode.next
def reverse(self):
first = self.head
second = first.next
while second:
temp = second.next
second.next = first
first = second
second = temp
我在前面加上一个 [8,7,11,6,5,10] 的列表。 当我尝试使用反向功能并尝试打印时,我得到 8 和 7 的无限循环。我不知道为什么。我认为第一个已经指向 self.head ,所以当它改变时, self.head 也会改变。但事实并非如此。有人可以帮我解决这个问题吗?
【问题讨论】:
-
first = second部分的用途是什么?你不打算对first.next做点什么吗? -
第一 = 第二部分旨在重新分配对象。与 exp 一样,当 first = 8,7,11,6,5,10 然后 second.next 将是:8, 7,11,6,5,10 然后 first 将被重新分配为 7,8,7,11 ,6,5,10。它一直持续到类的所有数据属性都处于反向位置
-
尝试在纸上绘制图表以跟踪过程。确保你understand how names work in Python。
-
谢谢@KarlKnechtel。现在我认为第二个节点指向创建 self.head 无限循环的第一个节点,这可以通过在循环后分配 self.head = first 来修复
标签: python data-structures linked-list