题解 | #【模板】栈#

【模板】栈

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())


全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 14:23
steelhead:你回的有问题,让人感觉你就是来学习的
点赞 评论 收藏
分享
完美的潜伏者许愿简历...:隐藏信息被你提取出来了,暗示,这就是暗示
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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