백준 10866 - 덱

김예림·2025년 4월 21일

문제 파악

덱을 가지고 이리저리 활용해보는 문제

덱은 앞으로도 뒤로도 넣을 수 있고 뺄수도 있는 자료구조
스택과 큐를 혼합한 자료구조!!

명령어에 따라 주어진 명령을 수행하는 문제

풀이

  1. 명령의 수 N을 입력받는다.
  2. N번 반복하면서 명령어를 하나씩 읽는다.
    a. 명령어에 따라 덱을 조작한다.
    b. 출력값은 하나씩 스트링빌더에 넣는다.

코드

import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

public class 덱 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        //nextInt는 줄바꿈 처리를 안해줘서 따로 해주기기
        sc.nextLine();

        Deque<Integer> deque = new LinkedList<>();
        StringBuilder sb = new StringBuilder();

        for (int i=0; i<N; i++) {
            //입력한 명령어 한 줄을 문자열 배열에 저장
            //ex) push_back 1 => cmd[0] = push_back, cmd[1] = "1"
            //입력에 띄어쓰기가 없을 경우 cmd.length = 1
            String[] cmd = sc.nextLine().split(" ");

            switch (cmd[0]) {
                case "push_front":
                    //문자열이기 때문에 정수로 변환 필요요
                    deque.addFirst(Integer.parseInt(cmd[1]));
                    break;
                case "push_back":
                    deque.addLast(Integer.parseInt(cmd[1]));
                    break;
                case "pop_front":
                    //만약 덱이 비어있으면 -1을 넣고 아니면 가장 위에 있는 값을 빼서 넣어주기
                    sb.append(deque.isEmpty() ? -1 : deque.pollFirst()).append("\n");
                    break;
                case "pop_back":
                    sb.append(deque.isEmpty() ? -1 : deque.pollLast()).append("\n");
                    break;
                case "size":
                    sb.append(deque.size()).append("\n");
                    break;
                case "empty":
                    sb.append(deque.isEmpty() ? 1 : 0).append("\n");
                    break;
                case "front":
                    sb.append(deque.isEmpty() ? -1 : deque.peekFirst()).append("\n");
                    break;
                case "back":
                    sb.append(deque.isEmpty() ? -1 : deque.peekLast()).append("\n");
                    break;
            }
        }
        System.out.println(sb.toString());
    }
}

0개의 댓글