题解 | 【模板】栈 arr=arr[:-1] # 会超时arr.pop() # 不会超时

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

import sys

# for line in sys.stdin:
#     a = line.split()
#     print(int(a[0]) + int(a[1]))
def solver():
    cmd=[]
    arr=[]
    n =int(input())
    for i in range(n):
        cmd.append(input())
    for line in cmd:
        
        if "push" in line:
            arr.append(line.split(" ")[1] )
        elif line=="pop":
            if len(arr)>0:
                ret=arr[-1]
                #arr=arr[:-1]  # 会超时
                arr.pop()  # 不会超时
                print(ret)
            else:
                print("error")
        elif line=="top":
            if len(arr)>0:
                print(arr[-1])
            else:
                print("error")
solver()
        
    

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务