Published:
Updated:


Solution

import collections
import sys
from typing import List


def solution(commands: List[List[str]]) -> List[int]:
    answer = []
    stack = collections.deque()

    for command in commands:
        x1, x2 = '', ''
        if len(command) == 2:
            x1, x2 = command[0], command[1]
        else:
            x1 = command[0]

        my_push(stack, x1, x2)
        my_pop(answer, stack, x1)
        my_size(answer, stack, x1)
        my_empty(answer, stack, x1)
        my_top(answer, stack, x1)

    return answer


def my_top(answer, stack, x1):
    if x1 == 'top':
        if not stack:
            answer.append(-1)
        else:
            answer.append(stack[-1])


def my_empty(answer, stack, x1):
    if x1 == 'empty':
        if not stack:
            answer.append(1)
        else:
            answer.append(0)


def my_size(answer, stack, x1):
    if x1 == 'size':
        answer.append(len(stack))


def my_pop(answer, stack, x1):
    if x1 == 'pop':
        if stack:
            popped = stack.pop()
            answer.append(popped)
        else:
            answer.append(-1)


def my_push(stack, x1, x2):
    if x1 == 'push':
        stack.append(x2)


N = int(input())
array = []
for _ in range(N):
    array.append(sys.stdin.readline().split())

print(*solution(array), sep='\n')

Leave a comment