문제
https://www.acmicpc.net/problem/18258
풀이
Deque 구현체로 풀었다.
소스코드
package queue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
public class BOJ18258 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = null;
int N = Integer.parseInt(br.readLine());
Deque<Integer> deque = new ArrayDeque<Integer>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < N; i++){
st = new StringTokenizer(br.readLine());
String command = st.nextToken();
switch(command) {
case "push":
deque.push(Integer.parseInt(st.nextToken()));
break;
case "front":
if(deque.isEmpty()){
sb.append(-1).append("\n");
} else {
sb.append(deque.peekLast()).append("\n");
}
break;
case "back":
if(deque.isEmpty()){
sb.append(-1).append("\n");
} else {
sb.append(deque.peekFirst()).append("\n");
}
break;
case "size":
sb.append(deque.size()).append("\n");
break;
case "empty":
if(deque.isEmpty()) {
sb.append(1).append("\n");
} else {
sb.append(0).append("\n");
}
break;
case "pop":
if(deque.isEmpty()) {
sb.append(-1).append("\n");
} else {
sb.append(deque.pollLast()).append("\n");
}
break;
}
}
bw.write(sb.toString());
bw.flush();
}
}
'💡Problem Solving > BOJ' 카테고리의 다른 글
[BOJ 5430] AC (Java) (0) | 2021.11.15 |
---|---|
[BOJ 1021] 회전하는 큐 (Java) (0) | 2021.11.14 |
[BOJ 4949] 균형잡힌 세상 (Java) (0) | 2021.11.14 |
[BOJ 9012] 괄호 (Java) (0) | 2021.11.14 |
[BOJ 17298] 오큰수 (Java) (0) | 2021.11.13 |