Python(链接列表) - 属性错误

时间:2015-02-03 22:07:48

标签: python linked-list

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

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self, new_data):
        self.data = new_data

    def set_next(self, new_next):
        self.next = new_next

    def __str__(self):
        return self.data

class LinkedListIterator:
    def __init__( self, head):
        self.current = head

    def __next__( self ):
        if self.current != None:
            item = self.current.get_data()
            self.current = self.current.get_next()
            return item
        else :
            raise StopIteration

class UnorderedList:

    def __init__(self):
        self.head = None

    def add(self, item): #add to the beginning of the list
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.get_next()
        return count

    def is_empty(self):
        return self.head == None

    def search(self,item):
        current = self.head
        while current != None:
            if current.get_data() == item:
                return True
            else:
                current = current.get_next()
        return False

    def remove(self, item):
        #Assumes the item is in the linked list
        current = self.head
        previous = None
        found = False
        while not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()
        if previous == None:
            self.head = current.get_next() #remove the first node
        else:
            previous.set_next(current.get_next())


#Iterator

    def __iter__(self):
        return LinkedListIterator(self.head)

    def get(self,pos):
        current = self.head
        for i in range(0, pos):
            current = current.next
        return(current.data)

出于某种原因,每当我运行测试用例时:

my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
    my_list.add(x)
print(my_list.get(6))

我总是遇到"属性错误:' NoneType'对象没有属性'数据""

我发现这很奇怪,我以为我被允许像在python中那样返回?我无法弄清楚错误是什么。有人会照顾我吗?

0 个答案:

没有答案