我对python有点陌生,我已经看到了解决反向链接列表问题的正确解决方案,但是我想知道为什么我的解决方案不起作用。特别地,由于“ new_list.head.next = prev”这一行,反向函数停留在以下代码的while循环内

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def __iter__(self):
        node = self.head
        while node:
            yield node.value
            node = node.next

    def __repr__(self):
        return str([v for v in self])

def reverse(linked_list):
    new_list = LinkedList()
    if linked_list is None:
        return new_list
    node = linked_list.head
    new_list.head = node
    while node.next:
        prev = node
        node = node.next
        new_list.head = node
        new_list.head.next = prev
    return new_list

if __name__ == "__main__":
    a = LinkedList()
    b = [1,2,3,4,5]
    for item in b:
        a.append(item)
    print a
    c = reverse(a)
    print c

最佳答案

如果您用Python3标记问题,请确保它在python 3中运行。

原因是因为您混淆了点并创建了无限循环。打印value,它可能会帮助您查找错误。我将使用这些值指出问题。

    while node.next:
        # First node that comes in value = 1
        print(node.value) #
        prev = node # prev = 1
        node = node.next # node = 2
        new_list.head = node # You are setting the head = 2 (i.e. head = node.next)
        new_list.head.next = prev # You are setting next of head = 1 (i.e. head.next = node.next.next)
        # however this also set node.next.next = 1
        # So going into the next loop: node.value = 2 and node.next.value = 1


由于指针混乱,您将永远在第一个节点和第二个节点之间循环。

关于python - 在python中反转链接列表时无法访问链接列表的下一个节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56194314/

10-12 18:11