创建列表/节点类 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14920940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:51:44  来源:igfitidea点击:

Create list/node class Python

python

提问by SagittariusA

As exercise, I would like to create my own node/list class. Anyway I don't understand how to add a node to list...here's my code:

作为练习,我想创建自己的节点/列表类。无论如何,我不明白如何将节点添加到列表中……这是我的代码:

class Node:
    def __init__(self, value):
        self.element = value
        self.nextEl = None

    def getEl(self):
        return self.element

    def getNext():
        return self.nextEl

class List:
    def __init__(self, fnode):
        self.firstNode = fnode

    def add(self, newNode):

    def printList(self):
        temp = self.firstNode
        while (temp != None):
            print temp.element
            temp = temp.nextEl

回答by Martijn Pieters

You need to find the last node without a .nextElpointer and add the node there:

您需要找到没有.nextEl指针的最后一个节点并在那里添加节点:

def add(self, newNode):
    node = self.firstNode
    while node.nextEl is not None:
        node = next.nextEl
    node.nextEl = newNode

Because this has to traverse the whole list, most linked-list implementations also keep a reference to the last element:

因为这必须遍历整个列表,大多数链表实现还保留对最后一个元素的引用:

class List(object):
    first = last = None

    def __init__(self, fnode):
        self.add(fnode)

    def add(self, newNode):
        if self.first is None:
            self.first = self.last = newNode
        else:
            self.last.nextEl = self.last = newNode

Because Python assigns to multiple targets from left to right, self.last.nextElis set to newNodebefore self.last.

因为 Python 从左到右分配给多个目标,self.last.nextEl所以设置为newNodebefore self.last

Some style notes on your code:

关于您的代码的一些样式说明:

  • Use is Noneand is not Noneto test if an identifier points to None(it's a singleton).
  • There is no need for accessors in Python; just refer to the attributes directly.
  • Unless this is Python 3, use new-style classes by inheriting from object:

    class Node(object):
        # ...
    
  • 使用is Noneis not None测试标识符是否指向None(它是一个单例)。
  • Python 中不需要访问器;直接引用属性就行了。
  • 除非这是 Python 3,否则通过继承使用新式类object

    class Node(object):
        # ...