Python:使用 LinkedLists,无法添加



我是第一次玩链表,我似乎不明白为什么我的 add 方法不起作用。

这是我的代码:

    class Node(object):
        def __init__(self, datain):
            self.data = datain
            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.data = newnext


    class UnorderedList(object): # also known as linked list
        def __init__(self):
            self.head = None
        def isEmpty(self):
            return self.head == None
        def add(self, item):
            temp = Node(item)
            temp.setNext(self.head)
            self.head = temp
        def size(self):
            current = self.head
            count = 0
            while current != None:
                count = count + 1
                current = current.getNext()
            return count
        def search(self, item):
            current = self.head
            found = False
            while current != None and not found:
                if current.getData == item:
                    found = True
                else:
                    current = current.getNext()
            return found
mylist = UnorderedList()
print mylist.size()
mylist.add(6)
print mylist.size()
mylist.add(9)
print mylist.size()

但是我没有得到预期的结果,这是我的终端显示的内容:

$ python linkedlist.py
0
1
1

添加方法似乎不起作用,但我不知道为什么。作为参考,我一直在使用它来学习。

替换:

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

跟:

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

相关内容

  • 没有找到相关文章

最新更新