문제
풀이
JDK에서 기본적으로 제공하는 큐를 사용하거나 큐를 직접 구현하여 풀이할 수 있다.
BufferedReader 또는 Scanner를 이용해 입력받고, switch문을 사용해 명령별로 작성해주면 된다.
1. 기본 큐 인터페이스 사용
Queue<Integer> queue=new LinkedList<>();
큐 객체를 선언하려면 위와 같이 사용하면 된다. 정수형 데이터를 입력받는 문제이므로 자료형은 Integer로 설정한다.
(큐에 대한 더 자세한 내용은 여기)
Queue (Java SE 21 & JDK 21)
Type Parameters: E - the type of elements held in this queue All Superinterfaces: Collection , Iterable All Known Subinterfaces: BlockingDeque , BlockingQueue , Deque , TransferQueue All Known Implementing Classes: AbstractQueue, ArrayBlockingQueue, ArrayD
docs.oracle.com
기본 메소드는 위와 같다. 이들을 이용하면 push, pop, size, empty, front 명령을 처리할 수 있다.
StringTokenizer 또는 split()을 사용해 입력 문자열을 띄어쓰기 단위로 분리해 주고(아래 풀이에서는 StringTokenizer 사용) cmd에 따른 switch문을 작성하면 끝난다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Queue<Integer> queue=new LinkedList<>();
StringTokenizer st;
int num=0;
int N=Integer.parseInt(in.readLine());
for(int i=0; i<N; i++) {
st=new StringTokenizer(in.readLine());
String cmd=st.nextToken();
switch(cmd) {
case "push":
num=Integer.parseInt(st.nextToken());
queue.offer(num);
break;
case "pop":
if(queue.isEmpty())
System.out.println(-1);
else
System.out.println(queue.poll());
break;
case "size":
System.out.println(queue.size());
break;
case "empty":
if(queue.isEmpty())
System.out.println(1);
else
System.out.println(0);
break;
case "front":
if(queue.isEmpty())
System.out.println(-1);
else
System.out.println(queue.peek());
break;
case "back":
if(queue.isEmpty())
System.out.println(-1);
else
System.out.println(num);
}
}
}
}
2. 큐를 직접 구현
위 코드와 흐름은 동일하지만, 기본 큐 인터페이스를 사용하지 않고 직접 구현하여 사용한다.
참고 링크는 여기
원형큐
선형큐의 문제점- front와 rear의 값이 계속 증가만 하기 때문에 언젠가는 배열의 끝에 도달- 배열의 앞부분이 비어 있더라도 사용하지 못함- 따라서 주기적으로 모든 요소를 왼쪽으로 이동시켜야
sysouthelloworld.tistory.com
위 링크에서는 C로 구현되어 있지만, 전체적인 방법은 동일하다.
public class Queue {
int front, rear;
Object[] data;
int MAX_QUEUE_SIZE;
public Queue(int size) {
front=rear=0;
MAX_QUEUE_SIZE=size;
try {
data=new Object[MAX_QUEUE_SIZE];
}catch(OutOfMemoryError e) {
MAX_QUEUE_SIZE=0;
}
}
public boolean isEmpty() {
return front==rear;
}
public boolean isFull() {
return ((rear+1)%MAX_QUEUE_SIZE==front);
}
public void enqueue(Object item) {
if(isFull())
System.out.println("포화 상태");
rear=(rear+1)&MAX_QUEUE_SIZE;
data[rear]=item;
}
public Object dequeue() {
if(isEmpty())
System.out.println("공백 상태");
front=(front+1)%MAX_QUEUE_SIZE;
return data[front];
}
public Object peek() {
if(isEmpty())
System.out.println("공백 상태");
return data[(front+1)%MAX_QUEUE_SIZE];
}
public int capacity() {
return MAX_QUEUE_SIZE;
}
public int size() {
return rear;
}
...
}
'백준' 카테고리의 다른 글
백준 18258: 큐 2(java) (0) | 2024.07.15 |
---|---|
백준 12789: 도키도키 간식드리미(java) (0) | 2024.07.15 |
백준 4949: 균형잡힌 세상(java) (0) | 2024.07.12 |
백준 10773: 제로(java) (0) | 2024.07.12 |
백준 28278: 스택 2(java) (0) | 2024.07.12 |