带有节点的Python链接列表。可迭代

时间:2015-02-04 08:23:37

标签: python linked-list listiterator

我需要帮助为__iter__()课程编写UnorderedList()方法。我试过这个:

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

但是while循环并没有停止。这是我的其他类和代码:

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

1 个答案:

答案 0 :(得分:5)

如果要继续迭代所有项目,则应该

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

这样你就可以在每一步中更进一步。

BTW,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