Skip to main content
 首页 » 编程设计

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

2025年05月04日21tuyile006

我对 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 

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