带节点的 Python 链表。可迭代的

标签 python linked-list listiterator

我需要一些帮助来为我的 UnorderedList() 类编写一个 __iter__() 方法。我试过这个:

def __iter__(self):
    current = self
    while current != None:
        yield current

但是 while 循环不会停止。这是我的其余类(class)和代码:

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

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

class UnorderedList:

    def __init__(self):
        self.head = None
        self.count = 0

最佳答案

如果你想成功地迭代所有项目,你应该这样做

def __iter__(self):
    # Remember, self is our UnorderedList.
    # In order to get to the first Node, we must do
    current = self.head
    # and then, until we have reached the end:
    while current is not None:
        yield current
        # in order to get from one Node to the next one:
        current = current.next

让您在每一步都更进一步。

顺便说一句,setter 和 getter 不以方法的形式在 Python 中使用。如果您需要它们,请使用属性,否则完全忽略它们。

就这样吧

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

class UnorderedList(object):

    def __init__(self):
        self.head = None
        self.count = 0

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current
            current = current.next

关于带节点的 Python 链表。可迭代的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28316668/

相关文章:

python - Odoo继承日历并将公共(public)假期添加到日历 View 中

快速获取多个链表偏序的算法

c++ - 链接列表中的删除显示 "0"

java - 如何在JAVA中显示多个LinkedList元素看起来像一个表格?

c++ - 如何制作指针迭代器?

python - 在 Python 中打开文本文件时出现问题

python - 当我运行我的代码时,它返回 '[]' 。我怎样才能解决这个问题?

python - 如何在 reStructuredText 的代码块中强制使用空格

c++ - 循环链表算法

c++ - 双向解引用迭代器的返回类型