|
| 1 | +/* |
| 2 | +push_front X: 정수 X를 덱의 앞에 넣는다. |
| 3 | +push_back X: 정수 X를 덱의 뒤에 넣는다. |
| 4 | +pop_front: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다. |
| 5 | +pop_back: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다. |
| 6 | +size: 덱에 들어있는 정수의 개수를 출력한다. |
| 7 | +empty: 덱이 비어있으면 1을, 아니면 0을 출력한다. |
| 8 | +front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다. |
| 9 | +back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다. |
| 10 | +*/ |
| 11 | +import java.io.*; |
| 12 | +import java.util.*; |
| 13 | + |
| 14 | +class Main { |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 17 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 18 | + int n = Integer.parseInt(br.readLine()); |
| 19 | + |
| 20 | + StringBuilder result = new StringBuilder(); |
| 21 | + Deque<Integer> dq = new ArrayDeque<>(); |
| 22 | + |
| 23 | + while (n-- > 0) { |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + String command = st.nextToken(); |
| 26 | + if (command.equals("push_front")) { |
| 27 | + dq.offerFirst(Integer.parseInt(st.nextToken())); |
| 28 | + } else if (command.equals("push_back")) { |
| 29 | + dq.offerLast(Integer.parseInt(st.nextToken())); |
| 30 | + } else if (command.equals("pop_front")) { |
| 31 | + if (dq.isEmpty()) { |
| 32 | + result.append("-1\n"); |
| 33 | + } else { |
| 34 | + result.append(dq.pollFirst()).append("\n"); |
| 35 | + } |
| 36 | + } else if (command.equals("pop_back")) { |
| 37 | + if (dq.isEmpty()) { |
| 38 | + result.append("-1\n"); |
| 39 | + } else { |
| 40 | + result.append(dq.pollLast()).append("\n"); |
| 41 | + } |
| 42 | + } else if (command.equals("size")) { |
| 43 | + result.append(dq.size()).append("\n"); |
| 44 | + } else if (command.equals("empty")) { |
| 45 | + if (dq.isEmpty()) { |
| 46 | + result.append("1\n"); |
| 47 | + } else { |
| 48 | + result.append("0\n"); |
| 49 | + } |
| 50 | + } else if (command.equals("front")) { |
| 51 | + if (dq.isEmpty()) { |
| 52 | + result.append("-1\n"); |
| 53 | + } else { |
| 54 | + result.append(dq.peekFirst()).append("\n"); |
| 55 | + } |
| 56 | + } else { |
| 57 | + if (dq.isEmpty()) { |
| 58 | + result.append("-1\n"); |
| 59 | + } else { |
| 60 | + result.append(dq.peekLast()).append("\n"); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + bw.write(result.toString()); |
| 65 | + bw.flush(); |
| 66 | + bw.close(); |
| 67 | + } |
| 68 | +} |
0 commit comments