简体   繁体   English

用Python反转链接列表的方法

[英]Approach on Reversing a Linked List in Python

I tried the following code to reverse a linked list and is getting an infinite loop as an error. 我尝试下面的代码来反向链接列表,并得到无限循环作为错误。 Can you pls tell me what's wrong in this approach. 您能告诉我这种方法有什么问题吗?

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

There is a logic error in your method. 您的方法中存在逻辑错误。

At the end of the first pass of the while loop: 在while循环的第一遍结束时:

  • curr (2nd element in list) curr (列表中的第二个元素)
  • curr.next (1st element in list) curr.next (列表中的第一个元素)
  • temp = curr = (2nd element in list) temp = curr =(列表中的第二个元素)

In the second pass of the while loop. 在while循环的第二遍。 You expect to reach the 3rd element using temp.next. 您希望使用temp.next到达第3个元素。 This is wrong because: 这是错误的,因为:

  • temp.next = curr.next = (1st element in list) temp.next = curr.next = (列表中的第一个元素)

Leaving you to loop infinitely between the first and second element with no exit condition. 让您在没有退出条件的情况下在第一个元素和第二个元素之间无限循环。

I will leave you to figure out the proper solution for this. 我将让您找出解决方案。

(Hint: temp should be assigned to the ??? element in the 1st pass) (提示:应该在第一遍中将temp分配给???元素)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM