题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
# 创建一个栈类。和两个栈的方法,直接调用法法就好啦,可以有更简单的,但这样更直观
class Stack:
def __init__(self):
self.stack=[]
def push(self,element):
self.stack.append(element)
def pop(self):
if len(self.stack)==0:
return "error"
else:
return self.stack.pop(-1)
def top(self):
if len(self.stack)==0:
return "error"
else:
return self.stack[-1]
num = int(input())
st =Stack()
for i in range(num):
str_num = input()
str_list = str_num.split(" ")
if str_list[0]=="push":
st.push(int(str_list[1]))
elif str_list[0]=="pop":
print(st.pop())
else:
print(st.top())