[英]Infinite loop while reversing a linked list in Python
So I have this code所以我有这个代码
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
I prepend and then have a list of [8,7,11,6,5,10].我在前面加上一个 [8,7,11,6,5,10] 的列表。 When I try to use the reverse function and try to print out I get infinite loop of 8 and 7. I'm not sure why.
当我尝试使用 reverse 函数并尝试打印出来时,我得到了 8 和 7 的无限循环。我不知道为什么。 I thought the first already points to the self.head so that when it gets changed, the self.head gets changed as well.
我认为第一个已经指向 self.head,所以当它改变时,self.head 也会改变。 But its not the case.
但事实并非如此。 Could someone please help me with this?
有人可以帮我解决这个问题吗?
Your reverse
method is focussing on only the first two elements, and setting up cyclic references between them.您的
reverse
方法仅关注前两个元素,并在它们之间设置循环引用。
Here's the modified reverse()
method, that works.这是修改后的
reverse()
方法,它有效。 (Note that the reverse()
method contains an enclosed helper function called rev_()
, which recurses through the linked list): (注意
reverse()
方法包含一个名为rev_()
的封闭辅助函数,它通过链表递归):
def reverse (self): #------------MODIFIED--------------
def rev_ (head):
rest = head.next
if rest is None:
return head
else:
reversed_rest = rev_(rest)
rest.next = head
head.next = None
return reversed_rest
if self.head is not None:
self.head = rev_(self.head)
Testing it out:测试一下:
my_list = LinkedList()
my_list.print_list()
print()
my_list.reverse()
my_list.print_list()
print()
my_list.prepend(21)
my_list.print_list()
print()
my_list.reverse()
my_list.print_list()
print()
my_list.prepend(22)
my_list.prepend(23)
my_list.print_list()
print()
my_list.reverse()
my_list.print_list()
Output:输出:
Empty
Empty
21
21
23 22 21
21 22 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.