public class Queue {
private int max;
private int front;
private int rear;
private int num; //현재 큐에 들어있는 수들의 개수
private int[] que;
public class EmptyQueueException extends RuntimeException {
}
public class OverflowQueueException extends RuntimeException {
}
public Queue(int capacity) {
max = capacity;
front = 0;
rear = 0;
num = 0;
try {
que = new int[max];
}catch (OutOfMemoryError e) {
max = 0;
}
}
public int enqueue(int x) throws OverflowQueueException {
if (num >= max)
throw new OverflowQueueException();
que[rear++] = x;
num++;
if (rear == max) {
rear = 0;
}
return x;
}
public int dequeue() throws IntStack.EmptyStackException {
if (num <= 0)
throw new EmptyQueueException();
int x = que[front++];
num--;
if (front == max)
front = 0;
return x;
}
public int peek() throws EmptyQueueException{ //프론트 데이터 조회
if (num <= 0)
throw new EmptyQueueException();
return que[front];
}
public int indexOf(int x) { //x가 큐 안에 있는지 검색
for (int i = 0; i < num; i++) {
int idx = (i + front) % max;
if (que[idx] == x)
return idx;
}
return -1;
}
public void clear() {
num = front = rear = 0;
}
public int capacity() {
return max;
}
public int size() {
return num;
}
public boolean isEmpty() {
return num <= 0;
}
public boolean isFull() {
return num >= max;
}
public void dump() { //모든 데이터를 프론트에서 리어 순으로 출력
if (num <= 0)
System.out.println("큐가 비었습니다");
else {
for (int i = 0; i < num; i++) {
System.out.println(que[(i+front) % max] + " ");
}
System.out.println();
}
}
}