【问题标题】:Approach on Reversing a Linked List in Python在 Python 中反转链表的方法
【发布时间】:2018-12-13 06:05:00
【问题描述】:

我尝试了以下代码来反转链表,并得到一个无限循环作为错误。你能告诉我这种方法有什么问题吗?

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

【问题讨论】:

    标签: python data-structures linked-list reverse


    【解决方案1】:

    您的方法存在逻辑错误。

    在第一次while循环结束时:

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

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

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

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

    我会让你找出正确的解决方案。

    (提示:temp 应该在第 1 遍中分配给 ??? 元素)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多