큐도 마찬가지로 배열을 이용하여 해결했다.
큐의 특성상 선입 선출(FIFO)를 구현하기 위해 변수를 이용 하였다.
tail = 가장 최근에 push된 위치
head = 가장 먼저 push된 위치
1 (head) | 2 | 3 | 4 (tail) |
<전체 코드>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Problem10845 {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] queue = new int[10000];
int head = 0;
int tail = 0;
for(int i=0; i<N; i++){
String str = scanner.next();
if(str.equals("push")){
queue[tail]=scanner.nextInt();
tail++;
}
else if(str.equals("pop")){
if(tail-head==0){
System.out.println("-1");
}
else {
System.out.println(queue[head]);
head++;
}
}
else if(str.equals("size")){
if(tail-head==0){
System.out.println("0");
}
else {
System.out.println(tail - head);
}
}
else if(str.equals("empty")){
if(tail-head==0){
System.out.println("1");
}
else{
System.out.println("0");
}
}
else if(str.equals("front")){
if (tail - head == 0) {
System.out.println("-1");
}else {
System.out.println(queue[head]);
}
}
else if(str.equals("back")){
if(tail-head==0){
System.out.println("-1");
}
else{
System.out.println(queue[tail-1]);
}
}
}
}
}
'알고리즘 > 스택 큐' 카테고리의 다른 글
프로그래머스 - 프로세스(Java) (0) | 2025.01.02 |
---|---|
프로그래머스 - 올바른 괄호(Java) (0) | 2025.01.02 |
프로그래머스 - 기능개발(Java) (0) | 2025.01.01 |
프로그래머스 - 같은 숫자는 싫어(Java) (1) | 2024.12.31 |
백준 10828번 스택 (0) | 2024.12.30 |