链接列表不能正常工作?

时间:2017-07-23 22:48:40

标签: python

这应该是一个链表,每当文件中的一行通过循环时,它就会获得一个新节点。这只是我代码的一部分,但其他一切都运行正常,所以我认为包含所有内容都不相关。

我遇到的问题是节点没有正确添加。如果我在此之后立即打印(头)并打印(头[' next']),它会打印头节点的正确信息,但对于头部[' next']它打印"无",即使有足够的行已经通过头程序[' 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']

2 个答案:

答案 0 :(得分:0)

没有看到更多代码,你忘了将旧头分配给这个新节点

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

答案 1 :(得分:0)

主要问题是你写道:

newNode = head['next']

在最后一行,它应该是:

head['next'] = newNode

以便head字典链接到newNode

此外data[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?
相关问题