在python中实现链表中的追加功能

时间:2017-12-17 00:40:54

标签: python data-structures

我正在尝试在python中编写list.append()操作。我实现了一个链表,它工作正常。但我没有得到最后一个要打印的数据项。当我尝试打印列表中的所有项目时,我得到打印节点内的所有数据值,除了最后一个。我打印'无'而不是值。我在新添加的节点中将下一个指针指定为“无”时犯了一些错误。需要帮助修复。

Node类和List类的实现。

class Node:
   def __init__(self,item):
      self.data = item
      self.next = None
   def getData(self):
      return self.data
   def getNext(self):
      return self.next
   def setData(self,newItem):
      self.data = newItem
   def setNext(self, newNext):
      self.next = newNext
class UnorderedList:
   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):
       count = 0
       current = self.head
       while current != None:
          count = count + 1
          current = current.getNext()
    def append(self, item):
       current = self.head
       isEnd = False
       newItem = Node(item)
       while not isEnd:
          if current.getNext() == None:
              isEnd = True
          else:
              current = current.getNext()
      current = current.setNext(newItem)
      newItem = current.getNext()
  def printList(self):
      current = self.head
      isEnd = False
      while not isEnd:
          if current.getNext() == None:
              isEnd = True
          else:
              print current.getData()
              current = current.getNext()

我创建一个对象并传递值。

mylist = UnorderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
mylist.append(12)
print(mylist.size())
mylist.append(15)
print(mylist.size())
print('\n')
print mylist.printList()

输出是:

6
7
8

54
26
93
17
77
31
12
None

1 个答案:

答案 0 :(得分:0)

问题是你在做什么

  

打印(mylist.printList())

而printList()实际上并没有返回任何内容。这是那里印刷的最后一个。

希望这会有所帮助:

current = self.head
while(current!=None):
      print(current.getData())
      current=current.getNext()

这应该放在printlist中。

并且这样称呼:

mylist.printlist()
54
26
93
17
77
31
12
15

编辑: 我还修改了你的追加功能:

def append(self, item):
    print("append",item)
    current = self.head
    isEnd = False
    newItem = Node(item)
    while not isEnd:
        if current.getNext() == None:
            isEnd = True
        else:
            current = current.getNext()
    print("\Appending to",current.getData())
    current.setNext(newItem)
    current=current.getNext()
    print("\tAppended",current.getData())