https://www.acmicpc.net/problem/28278
✨ 문제
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
- 1 X: 정수 X를 스택에 넣는다. (1 ≤ X ≤ 100,000)
- 2: 스택에 정수가 있다면 맨 위의 정수를 빼고 출력한다. 없다면 -1을 대신 출력한다.
- 3: 스택에 들어있는 정수의 개수를 출력한다.
- 4: 스택이 비어있으면 1, 아니면 0을 출력한다.
- 5: 스택에 정수가 있다면 맨 위의 정수를 출력한다. 없다면 -1을 대신 출력한다.
내 코드
import sys
input = sys.stdin.readline
def stack(list, x) :
list.append(x)
return list
def pop(list) :
if len(list) == 0 :
print(-1)
else :
a = list.pop()
print(a)
return list
def check(list) :
print(len(list))
def is_empty(list) :
if len(list) == 0 :
print(1)
else : print(0)
def pop_noremove(list) :
if (len(list) == 0) :
print(-1)
else : print(list[-1])
def main() :
N = int(input().strip())
array = []
for i in range(N) :
order = input().strip().split()
if order[0] == '1' :
stack(array, int(order[1]))
elif order[0] == '2' :
pop(array)
elif order[0] == '3' :
check(array)
elif order[0] == '4' :
is_empty(array)
elif order[0] == '5' :
pop_noremove(array)
if __name__ == '__main__' :
main()
함수를 지정해서 기능을 구현하도록 만들었다
'알고리즘 > 백준' 카테고리의 다른 글
| 백준 2563번 : 색종이(S5) (0) | 2025.01.21 |
|---|---|
| 백준 12789번 : 도키도키 간식드리미(S3) (1) | 2025.01.21 |
| 백준 4949번 : 균형잡힌 세상(S4) (4) | 2025.01.20 |
| 백준 10773번 : 제로(S4) (0) | 2025.01.20 |
| 백준 2164번: 카드2(S4) (4) | 2023.12.25 |