큐는 스택과 마찬가지로 데이터를 쌓아두는 자료구조이다.
스택과 다른점은 스택은 LIFO(후입선출) 큐는 FIFO(선입선출)이다.
먼저 들어온 데이터가 먼저 나가게 된다.
public class IntQueue {
private int[] que;
private int capacity;
private int num;
private int front;
private int rear;
public class EmptyQueueException extends RuntimeException{
public EmptyQueueException(){}
}
public class OverFlowQueueException extends RuntimeException{
public OverFlowQueueException (){}
}
public IntQueue(int len) {
capacity = len;
front = rear = num = 0;
try {
que = new int[capacity];
} catch (OutOfMemoryError e) {
capacity = 0;
}
}
public int enque(int x) throws OverFlowQueueException{
if(num >= capacity) throw new OverFlowQueueException();
que[rear++] = x;
num ++;
if(rear == capacity)
rear = 0;
return x;
}
public int deque() throws EmptyQueueException{
if(num <= 0) throw new EmptyQueueException();
int x = que[front++];
num--;
if(front == capacity) front = 0;
return x;
}
public int peek() throws EmptyQueueException{
if(num <= 0) throw new EmptyQueueException();
return que[front];
}
public void clear(){
num = front = rear = 0;
}
public void dump(){
if(num <= 0) System.out.println("Empty");
else {
for (int i = 0; i < num; i++) {
System.out.print(que[(i + front) % capacity] + " ");
}
System.out.println();
}
}
public int indexOf(int x){
int idx;
for(int i = 0; i < num; i++){
idx = (i + front) % capacity;
if(que[idx] == x){
return idx;
}
}
return -1;
}
}
큐 활용 예시
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
IntQueue que = new IntQueue(10);
while(true){
System.out.println("(1) 인큐 (2) 디큐 (3) 피크 (4) 덤프 (5) 인덱스 (6) 초기화 (0) 종료");
int order = sc.nextInt();
if(order == 0) break;
int x;
switch (order){
case 1:
x = sc.nextInt();
que.enque(x);
break;
case 2:
x = que.deque();
System.out.println(x);
break;
case 3:
x = que.peek();
System.out.println(x);
break;
case 4:
que.dump();
break;
case 5:
x = sc.nextInt();
int res = que.indexOf(x);
System.out.println(res);
break;
case 6:
que.clear();
break;
default:
break;
}
}
}
}