题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
from os import X_OK import sys #from numpy import number #for line in sys.stdin: # a = line.split() # print(int(a[0]) + int(a[1])) #定义栈类,将push,top,和pop函数放入到栈类中 class Mystack(): def __init__(self): self.val=0 self.L=[] def push(self,x): self.L.append(x) self.val def top(self): x=self.L[-1] return x def pop(self): x=self.L.pop() return x #接收操作的个数 n = int(input()) #初始化栈对象 stack=Mystack() #将操作放入到Oprations操作列表中 opration =[] while n > 0: s = input() opration.append(s) n-=1 #遍历操作列表,分为三种情况 for x in opration: if x[0:4]=="push": number=int(x[4:]) stack.push(number) if x=="pop": try: print(stack.pop()) except: print("error") if x=="top": try: print(stack.top()) except: print("error")