[Java] 백준 28279 덱2

Lee GaEun·2024년 12월 3일

[Java] 알고리즘

목록 보기
27/93

28279 덱2 문제 링크

문제분석

  • 정수를 저장하는 덱을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성
  • 1 X: 정수 X를 덱의 앞에 넣음 (1 ≤ X ≤ 100,000)
  • 2 X: 정수 X를 덱의 뒤에 넣음 (1 ≤ X ≤ 100,000)
  • 3: 덱에 정수가 있다면 맨 앞의 정수를 빼고 출력
    • 없다면 -1 출력
  • 4: 덱에 정수가 있다면 맨 뒤의 정수를 빼고 출력
    • 없다면 -1 출력
  • 5: 덱에 들어있는 정수의 개수를 출력
  • 6: 덱이 비어있으면 1, 아니면 0을 출력
  • 7: 덱에 정수가 있다면 맨 앞의 정수를 출력
    • 없다면 -1 출력
  • 8: 덱에 정수가 있다면 맨 뒤의 정수를 출력
    • 없다면 -1 출력

제약 사항

입력 조건

첫째 줄 : 명령의 수 N (1 ≤ N ≤ 2,000,000)
둘째 줄 : 명령

출력 조건

출력해야하는 명령이 주어질 경우, 한 줄에 하나씩 출력

#1

  • 큐2랑 비슷함
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        Deque<Integer> arr = new ArrayDeque<>();

        int N = Integer.parseInt(br.readLine());

        for (int i = 0; i < N; i++) {
            String[] command = br.readLine().split(" ");

            if (command[0].equals("1")) {
                arr.addFirst(Integer.parseInt(command[1]));
            } else if (command[0].equals("2")) {
                arr.addLast(Integer.parseInt(command[1]));
            } else if (command[0].equals("3")) {
                bw.write((arr.isEmpty() ? "-1" : arr.pollFirst()) + "\n");
            } else if (command[0].equals("4")) {
                bw.write((arr.isEmpty() ? "-1" : arr.pollLast()) + "\n");
            } else if (command[0].equals("5")) {
                bw.write(arr.size() + "\n");
            } else if (command[0].equals("6")) {
                bw.write((arr.isEmpty() ? "1" : "0") + "\n");
            } else if (command[0].equals("7")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekFirst()) + "\n");
            } else if (command[0].equals("8")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekLast()) + "\n");
            }
        }

        bw.flush();
        bw.close();
    }
}

  • 성공
profile
I will give it my all (๑•̀o•́๑)ง

0개의 댓글