[문제]
https://www.acmicpc.net/problem/18258
[문제 풀이]
0. StringBuilder를 생성(마지막에 출력 할 문자열을 저장)
1. 명령 개수 N을 입력받는다
2. 정수를 저장할 Deque<Integer> queue를 생성
3. N개의 명령을 한 줄씩 처리
- push X: 정수 X를 큐에 넣는다
>> queue.addLast() 실행
- pop
- 비어있다면 -1
- 아니라면 그 수를 출력 >> pollFirst()
- size: 큐에 들어있는 정수의 개수를 출력
>> queue.size()
- empty: 비어있다면 1을 아니라면 0을 출력
- front: 비어있다면 -1을 아니라면 큐에 가장 앞에 있는 정수를 출력(peekFirst)
- back: 비어있다면 -1을 아니라면 큐의 가장 뒤에 있는 정수를 출력(peekLast)
[코드]
package bkjoon.queue;
import java.io.*;
import java.util.*;
public class queue018258 {
/**
* 백준(큐): 큐2(18258)
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
Deque<Integer> queue = new ArrayDeque<>();
int N = Integer.parseInt(br.readLine()); // 반복 횟수 입력받음
for(int i = 0; i < N; i++) {
String command = br.readLine();
if(command.startsWith("push")) {
int x = Integer.parseInt(command.split(" ")[1]); // 한칸 공백 이후 입력받는 숫자
queue.addLast(x);
}
else if (command.equals("pop")) {
// 가장 앞에 있는 정수를 빼고, 그 수를 출력한다, 정수가 없을 경우 -1을 출력한다.
sb.append(queue.isEmpty() ? -1 : queue.pollFirst()).append("\n");
}
else if (command.equals("size")) {
//큐에 들어있는 정수의 개수를 출력한다
sb.append(queue.size()).append("\n");
}
else if (command.equals("empty")) {
// 큐가 비어있으면 1, 아니면 0을 출력한다
sb.append(queue.isEmpty() ? 1 : 0).append("\n");
}
else if(command.equals("front")) {
//큐의 가장 앞에 있는 정수를 출력, 정수가 없다면 -1을 출력
sb.append(queue.isEmpty() ? -1 : queue.peekFirst()).append("\n");
}
else if(command.equals("back")) {
// 큐의 가장 뒤에있는 정수를 출력, 정수가 없다면 -1을 출력
sb.append(queue.isEmpty() ? -1 : queue.peekLast()).append("\n");
}
}
System.out.println(sb.toString());
}
}
'codingTest > 백준' 카테고리의 다른 글
| [codingTest][백준] 키로거📌 (0) | 2026.01.16 |
|---|---|
| [codingTest][백준] 균형잡힌 세상 (0) | 2026.01.12 |
| [백준][DFS] 바이러스 (0) | 2025.10.08 |
| [백준] 스택(10828) (0) | 2023.03.08 |
| [백준] 11654번 아스키 코드 (0) | 2022.07.22 |