728x90
https://www.acmicpc.net/problem/18258
● 문제
큐를 구현하면되는 아주 간단한 문제이다. 큐는 선입선출 자료구조로 말 그대로 먼저 들어간 요소가 먼저 나오는 방식이다. 자바에 있는 큐 라이브러리를 사용하면 맨 마지막에 있는 요소를 꺼내오는 함수가 없어 덱을 이용하여 구현하였다.
● 코드
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
Deque<Integer> q = new LinkedList<>();
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
String comment = st.nextToken();
if(comment.equals("push")) {
int num = Integer.parseInt(st.nextToken());
q.offer(num);
}
else if(comment.equals("pop")) {
Integer tmp = q.poll();
if(tmp == null) {
sb.append(-1).append('\n');
}
else {
sb.append(tmp).append('\n');
}
}
else if(comment.equals("size")) {
sb.append(q.size()).append('\n');
}
else if(comment.equals("empty")) {
if(q.isEmpty()) {
sb.append(1).append('\n');
}
else {
sb.append(0).append('\n');
}
}
else if(comment.equals("front")) {
Integer ite = q.peek();
if(ite == null) {
sb.append(-1).append('\n');
}
else {
sb.append(ite).append('\n');
}
}
else if(comment.equals("back")) {
Integer it = q.peekLast();
if(it == null) {
sb.append(-1).append('\n');
}
else {
sb.append(it).append('\n');
}
}
}
System.out.println(sb);
}
}
for문이 아닌 while문과 switch문으로 구성하면 더욱 깔끔한 코드를 만들 수 있을 것 같다.
728x90
'Study > BaekJoon' 카테고리의 다른 글
[백준 자바JAVA] 9093번 - 단어 뒤집기 (0) | 2024.07.27 |
---|---|
[백준 자바JAVA] 2606번 - 바이러스 (2) | 2024.07.23 |
[백준 자바JAVA] 11727번 - 2xn 타일링 2 (0) | 2024.07.19 |
[백준 자바JAVA] 9461번 - 파도반 수열 (0) | 2024.07.18 |
[백준 자바JAVA] 2579번 - 계단 오르기 (0) | 2024.07.17 |