用python写栈

时间:2023-12-19 11:08:02
class StackFullError(Exception):
pass class StackEmptyError(Exception):
pass class Stack:
def __init__(self, size):
self.size = size
self.lst = []
self.top = 0 # 下一个元素准备装的位置 def push(self, el):
if self.top == self.size:
raise StackFullError("栈满了") self.lst.insert(self.top, el)
self.top += 1 # 栈顶指针 def pop(self):
if self.top == 0:
raise StackEmptyError("栈空了")
self.top -= 1
return self.lst[self.top] s = Stack(6)
s.push("1")
s.pop() 未优化线程同步