점점 강해지고 있습니다.
[Java] 백준 10845번: 큐
풀이 방법
큐 구현 문제이다.
스택을 배열로 구현한 것처럼, 큐도 배열로 구현하였다.
선입선출큐을 특징으로 가지는 큐를 구현하기 위해서 pop 명령을 실행했을 때, 배열을 앞으로 하나씩 당기도록 만들었다.
풀이 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ_10845_큐 {
static int[] queue;
static int index;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
queue = new int[N];
index = 0;
for (int i = 0; i < queue.length; i++) {
String str = br.readLine();
int res = readOperator(str);
if(res >= -1)
System.out.println(res);
}
}
private static int readOperator(String operator) {
if(operator.length() >= 6) { // operator == push
queue[index] = Integer.parseInt(operator.split(" ")[1]);
index++;
} else if(operator.equals("empty")) { // operator == empty
return index == 0 ? 1 : 0;
} else if(operator.equals("size")) { // operator == size
return index;
} else if(index == 0) { // 인덱스가 0일 때 pop 또는 top 연산 시 -1 출력
return -1;
} else if(operator.equals("pop")) {
int num = queue[0] > 0 ? queue[0] : -1;
for (int i = 0; i < index; i++) {
queue[i] = queue[i+1];
}
index--;
return num;
} else if(operator.equals("front")) {
return queue[0];
} else if(operator.equals("back")) {
return queue[index-1];
}
return -2;
}
}
Thank You For Reading