python用連結串列實現堆疊(原創請勿轉載)
阿新 • • 發佈:2019-02-05
單向連結串列模組在我前面的部落格裡面
from 單向連結串列 import Linklist,Node class Stack: def __init__(self): self.__stack = Linklist() def push(self,node): self.__stack.insert_after(node) def pop(self): if not self.isEmpty(): lastNode = self.__stack.getTailNode() self.__stack.delete(lastNode) returnlastNode.id return -1 def isEmpty(self): return self.__stack.getLength() == 0 def display(self): current = self.__stack.head while current: print('我是元素{}'.format(current.data)) current = current.next def clear(self): self.__stack.head = Node if __name__ == '__main__': stack = Stack() stack.push(Node(20)) stack.push(Node(25)) print(stack.isEmpty()) print(stack.pop()) print(stack.pop()) print(stack.isEmpty()) print(stack.pop())