题解 | #【模板】栈#

【模板】栈

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

from os import error
import sys

class My_stack:
    def __init__(self):
        self.stack_list = []

    def push(self, input):
        self.stack_list.append(input)
    
    def pop(self):
        stack_len = len(self.stack_list)
        if stack_len == 0:
            print("error")
        else:
            last_id = stack_len - 1
            print(self.stack_list[last_id])
            self.stack_list.pop(last_id)
    
    def top(self):
        stack_len = len(self.stack_list)
        if stack_len == 0:
            print("error")
        else:
            last_id = stack_len - 1
            print(self.stack_list[last_id])


lines = []
for line in sys.stdin:
    a = line.split()
    lines.append(a)

one_stack = My_stack()
for line_id in range(int(lines[0][0])):
    one_line = lines[line_id+1]
    if one_line[0] == "push":
        one_stack.push(int(one_line[1]))
    elif one_line[0] == "pop":
        one_stack.pop()
    elif one_line[0] == "top":
        one_stack.top()

全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务