시간 제한 | 메모리 제한 | 제출 | 정답 | 맞힌 사람 | 정답 비율 |
---|---|---|---|---|---|
0.5 초 (추가 시간 없음) | 256 MB | 72008 | 34561 | 26708 | 49.098% |
정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
1
2
2
0
1
2
-1
0
1
-1
0
3
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class P_10845 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
Queue<Integer> queue = new LinkedList<>();
int back = 0;
for (int i = 0; i < n; i++) {
Object[] command = Arrays.stream(br.readLine().split(" ")).toArray();
if (command[0].equals("push")) {
back = Integer.parseInt((String) command[1]);
queue.add(back);
}
else if (command[0].equals("pop")) {
if (queue.isEmpty()) bw.write(-1 + "\n");
else bw.write(queue.remove() + "\n");
}
else if (command[0].equals("size")) bw.write(queue.size() + "\n");
else if (command[0].equals("empty")) {
if (queue.isEmpty()) bw.write(1 + "\n");
else bw.write(0 + "\n");
}
else if (command[0].equals("front")) {
if (queue.isEmpty()) bw.write(-1 + "\n");
else bw.write(queue.peek() + "\n");
}
else {
if (queue.isEmpty()) bw.write(-1 + "\n");
else bw.write(back + "\n");
}
}
bw.flush();
}
}
자바에서 큐는 LinkedList를 이용한다.
한 가지 신경써야 할 것은 back 명령어인데, 자바의 linkedlist에는 마지막 원소를 볼 수 있는 방법이 없다.
따라서 push를 할 때 그 원소를 변수에 저장하고 back 명령어 때 이 변수를 사용한다.