배고픈 개발자 이야기
2.10828 스택 본문
728x90
문제 - 정수를 저장하는 스택을 구현하는 문제
push N : 정수 N을 스택에 넣습니다.
pop : 스택의 맨 위의 정수를 빼고, 출력. 없는경우 -1 출력
size : 스택의 정수의 개수 출력
empty : 스택이 비어있으면 1, 아니면 0 출력
top : 스택의 가장 위의 정수를 출력, 없는경우 -1 출력
import sys
from sys import stdin,stdout
sys.setrecursionlimit(1500)
class Stack(list):
push = list.append
def is_empty(self):
if not self:
return True
else:
return False
def peek(self):
return self[-1]
def show(self):
data = str()
while self:
data += self.pop()
stdout.write(data + "\n")
d = Stack()
data = int(stdin.readline(15))
for _ in range(data):
cmd = stdin.readline(25)
if "push" in cmd:
val = int(cmd.strip().split(" ")[1])
d.push(val) # 오른쪽에 추가, 왼쪽에 추가하려면 appendleft()
elif "pop" in cmd:
if not d:
stdout.write(str(-1)+"\n")
else:
stdout.write(str(d.pop())+"\n") # 오른쪽 끝값을 가져오면서 제거, 왼쪽은 popleft()
elif "size" in cmd:
stdout.write(str(len(d))+"\n")
elif "empty" in cmd:
if d.is_empty():
stdout.write(str(1)+"\n")
else:
stdout.write(str(0)+"\n")
elif "top" in cmd:
if not d:
stdout.write(str(-1)+"\n")
else:
stdout.write(str(d.peek())+"\n") # 가장 왼쪽값, -1 가장 오른쪽값
'알고리즘 문제 > BAEKJOON' 카테고리의 다른 글
1000. A+B (feat.C++) (0) | 2019.09.17 |
---|---|
3.10845 큐 (0) | 2019.09.14 |
1.4740 (0) | 2019.09.14 |
0.1158 조세퍼스 문제 (feat.PYTHON) (0) | 2019.09.14 |
Comments