题解 | 【模板】栈的操作

【模板】栈的操作

https://www.nowcoder.com/practice/cdf02ea916454957b575585634e5773a

import sys
from collections import deque

class Stack:
    def __init__(self) -> None:
        self._stack = deque()
    
    def push(self,item):
        self._stack.append(item)
    
    def pop(self):
        if self.is_empty():
            raise IndexError("Empty")
        return self._stack.pop()
    def peek(self):
        if self.is_empty():
            raise IndexError("Empty")
        print(self._stack[-1])

    def is_empty(self):
        return len(self._stack) == 0

    def size(self):
        print(len(self._stack))

def handle_stack_operation (stack: Stack, cmd: str, n: int = 0):
    try:
        if cmd == "push":
            stack.push(n)
        if cmd == "pop":
            stack.pop()
        if cmd == "query":
            stack.peek()
        if cmd == "size":
            stack.size()
    except IndexError as e:
        print(e)



if __name__ == "__main__":
    k = 0
    stack = Stack()   
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        a = line.split()
        if k == 0:
            k = int(a[0])
            continue
        if len(a) == 1:
            handle_stack_operation (stack,a[0])
        elif len(a) == 2:
            handle_stack_operation (stack,a[0],int(a[1]))
        k -= 1
        if k == 0:
            break
        

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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