본문 바로가기
PS/solved.ac

[CLASS 2]백준 10828번, 10845번, 10866번 - 스택, 큐, 덱

by DawIT 2021. 1. 25.
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)

댓글