题解 | 【模板】栈
用python的list模拟stack
n = int(input())
class stack:
def __init__(self) -> None:
self.items = []
def push(self,x):
self.items.append(x)
def pop(self):
if self.items:
print(self.items.pop())
else:
print("error")
def top(self):
if self.items:
print(self.items[-1])
else:
print("error")
stack1 = stack()
for _ in range(n):
a = input().strip().split()
if len(a) == 1:
if a[0] == "pop":
stack1.pop()
else:
stack1.top()
else:
stack1.push(a[1])
查看5道真题和解析