[백준] 큐 2 18258번
나의 풀이
public class QueueV2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
Deque<Integer> queue = new LinkedList<>();
for(int i = 0; i < N; i++) {
String command = br.readLine();
if(command.contains("push")) {
queue.add(Integer.parseInt(command.split(" ")[1]));
} else if(command.equals("pop")) {
if(!queue.isEmpty()) {
sb.append(queue.poll()).append("\n");
} else {
sb.append(-1).append("\n");
}
} else if(command.equals("size")) {
sb.append(queue.size()).append("\n");
} else if(command.equals("empty")) {
if(queue.isEmpty()) {
sb.append(1).append("\n");
} else {
sb.append(0).append("\n");
}
} else if(command.equals("front")) {
Integer item = queue.peek();
if(item == null) {
sb.append(-1).append("\n");
} else {
sb.append(item).append("\n");
}
} else if(command.equals("back")) {
Integer item = queue.peekLast();
if(item == null) {
sb.append(-1).append("\n");
} else {
sb.append(item).append("\n");
}
}
}
System.out.println(sb);
}
}
- 큐는 FIFO(First In First Out) 으로 선입선출 구조이다. 큐를 실생활에서 찾아보자면 식당에 대기하기위해 우리는 줄을 서야한다. 이때, 먼저 와서 대기하는 손님먼저 들어가게된다.
- 큐의 구조만 알면 쉽게 풀 수 있는 문제이다.
- 하지만 처음에 시간초과가 자꾸 나서 고민에 빠졌다가 StringBuilder를 사용하니 통과하였다.