Python 链表工作不正常?

Python 链表工作不正常?,python,Python,这应该是一个链表,每当文件中的一行通过循环时,该链表都会获得一个新节点。这只是我代码的一部分,但是其他的一切都很好,所以我不认为把所有的代码都包含进去是有意义的 我遇到的问题是没有正确添加节点。如果我将print(head)和print(head['next'])紧跟在这之后,它会为head节点打印正确的信息,但对于head['next'],它会打印“None”,即使程序中已经有足够的行运行了head['next']以便在其中包含数据 我按照我找到的创建链接列表的说明进行了操作,但我一定是做错了

这应该是一个链表,每当文件中的一行通过循环时,该链表都会获得一个新节点。这只是我代码的一部分,但是其他的一切都很好,所以我不认为把所有的代码都包含进去是有意义的

我遇到的问题是没有正确添加节点。如果我将print(head)和print(head['next'])紧跟在这之后,它会为head节点打印正确的信息,但对于head['next'],它会打印“None”,即使程序中已经有足够的行运行了head['next']以便在其中包含数据

我按照我找到的创建链接列表的说明进行了操作,但我一定是做错了什么。我只是不知道是什么

if data[0] == "submit":
    node = {}
    node['data'] = data
    head = node
    head['next'] = None
    if len(data) > 1:
        if data[1] > "101":
            newNode = {}
            newNode = head['next']

在没有看到更多代码的情况下,您忘记将旧头分配给此新节点

node = {}
node["data"] = data # Sets data.
node["next"] = None # sets the next to none because there is no next as the head.
head["next"] = node # set the current heads next variable to this new node.
head = head["next"] # shift head to the new node by doing this.
尽管我是更多面向对象代码的粉丝,虽然在面向对象代码和脚本之间存在着一场战争,但这是一个定义类等的好地方,因为您已经在创建对象和分配静态键了,所以它更干净

下面是我整理的一个简单类:

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

    set_next(self, node):
        self.next = node

class LL:
    __init__(self):
        self.start = None
        self.end = None
        self.current = None


    appendNode(self, node):
        self.end.set_next(node)
        self.end = self.end.next


    appendData(self, data):
        self.appendNode(new Node(data))

    walk_list(self):
        self.current = self.start
        while self.current is not None:
            yield self.current
            self.current = self.current.next

主要问题是你写了:

newNode = head['next']
在最后一行,应该是:

head['next'] = newNode
这样
字典链接到
新节点

此外,
数据[1]>“101”
是可疑的,因为它将执行词典比较,而不是数字比较

您可能可以将脚本重写为:

if data[0] == "submit":
    # why do you assign the entire list as 'data'?
    node = {'data': data, 'next': None}
    head = node
    if len(data) > 1 and int(data[1]) > 101:  # numerical comparison?
        newNode = {}
        head['next'] = newNode
        newNode['data'] = data[1]  # assign second element?

为什么数据应该是“101”?你知道这是字符串比较吗?那么,如果你想要链表性能特征,为什么不使用内置的
列表
集合。deque
呢?我想他们可能正在了解LL是如何实现的。如果你对答案感到满意,请这样标记。