""" 栈 sstack.py 栈模型的顺序存储 重点代码 思路总结: 1.列表是顺序存储,但功能多,不符合栈的模型特征 2.利用列表,将其封装,提供接口方法 """ # 自定义异常类 class StackError(Exception): pass # 顺序栈类 class SStack: def __init__(self): # 空列表作为栈的存储空间,限制封装 # 列表的最后一个元素作为栈顶 self._elems = [] # 单下划线不希望类外使用 # 入栈 def push(self,val): self._elems.append(val) # 出栈,重新定义方法 def pop(self): if self.is_empty(): raise StackError("Stack is empty") return self._elems.pop() # 弹出并返回 # 判断列表是否为空 def is_empty(self): return self._elems ==[] # 空返回True # 查看栈顶元素 def top(self): if self.is_empty(): raise StackError("Stack is empty") return self._elems[-1] # ------------------------- print("-"*30) #if __name__ == " __main__": # st = SStack() # 初始化栈 # # 测试 # st.push(10) # st.push(20) # st.push(30) # while not st.is_empty(): # print(st.pop()) # ------------------------- """ 逆波兰表达式的实现,遇数字压入-push, 遇运算符弹出-pop 运算后再压入,P查看-top """ # st = SStack() # # while True: # exp = input("请输入:") # 1 2 5 4 + 1 4 p # tmp = exp.split(" ") # # print(tmp) # ['1', '2', '5', '4', '+', '1', '4', 'p'] # # for item in tmp: # if item not in ["+","-","*","/","p"]: # st.push(int(item)) # elif item == "+": # y = st.pop() # x = st.pop() # st.push(x + y) # elif item == "-": # y = st.pop() # x = st.pop() # st.push(x - y) # elif item == "*": # y = st.pop() # x = st.pop() # st.push(x * y) # elif item == "/": # y = st.pop() # x = st.pop() # st.push(x / y) # elif item == "p": # print(st.top())