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

时间:2019-05-17 22:32:51

标签: python python-3.x

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

3 个答案:

答案 0 :(得分:2)

如果您用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

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

答案 1 :(得分:2)

您的reverse的外观如下:

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

有了它,我得到了print c的期望输出:[5, 4, 3, 2, 1]

一般建议:创建新节点,而不是分配给初始列表中的节点。

答案 2 :(得分:1)

如果您想到两个参考文献,至少(至少对我来说)要容易一点:

•到您未曾看到的原始列表的其余部分
•在新列表的开头

在每次迭代时,将剩余部分向上移动,并将旧的剩余部分设置为新列表的开头。顺序在这里很重要-如您所见,如果不小心,很容易意外地在指向同一节点的两个不同变量上进行下一个更改:

def reverse(linked_list):
    new_list = LinkedList()

    if linked_list is None:
        return new_list

    remaining = linked_list.head

    while remaining:
        prev_head = new_list.head       # the old head becomes the first link
        new_list.head = remaining       # new head becomese the first remaining
        remaining = remaining.next      # move remaing one up the chain
        new_list.head.next = prev_head  # point the new head to the previous   
    return new_list