320x100
10828번 : 스택
스택을 구현하면 된다. 파이썬의 경우 list를 사용하여 push와 pop을 각각 append와 pop을 이용하여 간단하게 구현할 수 있다.
내 코드:
import sys
input = sys.stdin.readline
stack = []
for _ in range(int(input())):
cmd = input().split()
if cmd[0] == 'push':
stack.append(int(cmd[1]))
elif cmd[0] == 'pop':
if stack:
print(stack.pop())
else:
print(-1)
elif cmd[0] == 'size':
print(len(stack))
elif cmd[0] == 'empty':
print(int(not bool(stack)))
elif cmd[0] == 'top':
if stack:
print(stack[len(stack)-1])
else:
print(-1)
10845번 : 큐
큐 같은 경우 pop 만 달리해주고 front 와 back을 만들어주면 된다.
내 코드:
import sys
input = sys.stdin.readline
queue = []
for _ in range(int(input())):
cmd = input().split()
if cmd[0] == 'push':
queue.append(int(cmd[1]))
elif cmd[0] == 'pop':
if queue:
print(queue.pop(0))
else:
print(-1)
elif cmd[0] == 'size':
print(len(queue))
elif cmd[0] == 'empty':
print(int(not bool(queue)))
elif cmd[0] == 'front':
if queue:
print(queue[0])
else:
print(-1)
elif cmd[0] == 'back':
if queue:
print(queue[len(queue)-1])
else:
print(-1)
10866번 : 덱
덱은 큐와 스택을 합쳐놓은 듯한 만능 자료구조이다.
내 코드:
import sys
input = sys.stdin.readline
deque = []
for _ in range(int(input())):
cmd = input().split()
if cmd[0] == 'push_front':
deque.insert(0,int(cmd[1]))
elif cmd[0] == 'push_back':
deque.append(int(cmd[1]))
elif cmd[0] == 'pop_front':
if deque:
print(deque.pop(0))
else:
print(-1)
elif cmd[0] == 'pop_back':
if deque:
print(deque.pop())
else:
print(-1)
elif cmd[0] == 'size':
print(len(deque))
elif cmd[0] == 'empty':
print(int(not bool(deque)))
elif cmd[0] == 'front':
if deque:
print(deque[0])
else:
print(-1)
elif cmd[0] == 'back':
if deque:
print(deque[len(deque)-1])
else:
print(-1)
'PS > solved.ac' 카테고리의 다른 글
[CLASS 2]백준 1966번, 2805번, 1929번 (0) | 2021.01.27 |
---|---|
[CLASS 2]백준 11866번, 1654번, 1874번 (0) | 2021.01.27 |
[CLASS 2]백준 4949번, 9012번, 10773번, 10816번 (0) | 2021.01.25 |
[CLASS 2]백준 1978번, 2108번, 2164번 (0) | 2021.01.24 |
[CLASS 2]백준 7568번, 10814번, 11650번, 11651번, 1920번 (0) | 2021.01.23 |
댓글