python - 在python中反转链表时无法访问链表的下一个节点

标签 python python-3.x

我对 python 有点陌生,我已经看到了解决链表问题的正确解决方案,但我想知道为什么我的解决方案不起作用。特别是,由于“new_list.head.next=prev”行,reverse 函数保留在下面代码的 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/

相关文章:

python-3.x - 如果服务器没有在python3中以两种方式SSL身份验证请求客户端证书,如何停止握手和数据共享?

python - Asyncio 两个循环用于不同的 I/O 任务?

python - 在 Pandas 中编码列标签以进行机器学习

python - 如何使用Python CDK代码部署Java Lambda jar?

python - 从变量名或字符串创建列表或字典

python - 仅当问题存在时才显示问题评论

python - 枕头图像类型错误: an integer is required (got type tuple)

python - 统计模型的线性回归问题

本地机器上的 python udp socket.timeout

python - 无法按分位数选择 Pandas DataFrame