栈(stacks)是一种数据结构,是一种只能在一端进行插入和删除操作的特殊线性表, 它按照先进后出的原则存储数据(Last In First Out - LIFO)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Stack(object): def __init__(self): self.items = [] def is_empty(self): return self.items == [] def peek(self): if self.is_empty(): raise KeyError("stack is None") return self.items[len(self.items) - 1] def size(self): return len(self.items) def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise KeyError("stack is None") return self.items.pop()
if __name__ == '__main__' : a_stack = Stack() a_stack.push('一') a_stack.push('二') a_stack.push('三') print(a_stack.size()) print(a_stack.peek()) print(a_stack.pop()) print(a_stack.peek()) print(a_stack.size()) print(a_stack.is_empty()) a_stack.__init__() print(a_stack.is_empty())
|