题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
s = []
num = int(input())
for i in range(num):
a = input()
if a[0:4] == 'push':
s.append(int(a.split()[1]))
else:
if not s:
print('error')
else:
print(s[-1])
if a == 'pop':
s.pop()
# 为什么别人的比我快100ms?
# import sys
# s = input()
# lines = sys.stdin.read().splitlines()
# def stack(lines):
# arr = []
# for i in lines:
# if i == "pop":
# pop = arr.pop() if len(arr) >= 1 else "error"
# print(pop)
# elif i == "top":
# top = arr[-1] if len(arr) >= 1 else "error"
# print(top)
# else:
# pushNum = i.split()
# arr.append(pushNum[1])
# stack(lines)
上面是我自己写的,学一下ACM模式要怎么写,主要就是int(input()),还有split(),或者split(' ')。
另外输出就是print('error'),输出数值的话,就是print(s),print("hello",100,sep = ",",end = "")类似这种。
很关键的一点是:数组尽量用append增加,pop删除,否则很慢,会超时。(del(s[-1]的时间复杂度是O(n),pop()的复杂度是O(1),差太多啦!)
#日常刷题#

查看7道真题和解析