【问题标题】:Infinite loop while reversing a linked list in Python在Python中反转链表时的无限循环
【发布时间】: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


【解决方案1】:

您的reverse 方法只关注前两个元素,并在它们之间设置循环引用。

这是修改后的reverse() 方法,它有效。 (注意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)

测试一下:

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()

输出:

Empty

Empty

21 
21 
23 22 21 
21 22 23 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多