문제 풀러가기

10866

코드

import java.util.*;
import java.io.*;

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> deq = new LinkedList<>();

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

    for(int i = 0; i < n; i++) {
      String s = br.readLine();
      String[] arr = new String[2];
      arr = s.split(" ");

      if(arr[0].equals("push_front")) {
        int num = Integer.parseInt(arr[1]);
        deq.addFirst(num);
      } else if(arr[0].equals("push_back")) {
        int num = Integer.parseInt(arr[1]);
        deq.addLast(num);
      } else if(arr[0].equals("pop_front")) {
        bw.write(deq.isEmpty() ? "-1" : deq.pop() + "");
        bw.newLine();
      } else if(arr[0].equals("pop_back")) {
        bw.write(deq.isEmpty() ? "-1" : que.removeLast() + "");
        bw.newLine();
      } else if(arr[0].equals("size")) {
        bw.write(que.size() + "");
        bw.newLine();
      } else if(arr[0].equals("empty")) {
        bw.write(deq.isEmpty() ? "1" : "0");
        bw.newLine();
      } else if(arr[0].equals("front")) {
        bw.write(deq.isEmpty() ? "-1" : deq.peek() + "");
        bw.newLine();
      } else if(arr[0].equals("back")) {
        bw.write(deq.isEmpty() ? "-1" : deq.peekLast() + "");
        bw.newLine();
      }
    }

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

설명

큐와 유사하지만 앞에서 출력과 뒤에서 입력이 가능하다는 점이 다르다.