큐란? 선입선출
프론트: 첫번째데이터 위치
리어: 마지막데이터 한칸 뒤의 위치
인큐 → 저장후 리어 위치한칸 증가
디큐 → 꺼내고 프론트위치 한칸 증가
구현ex)
public class IntQueue {
private int [] que; //큐의 배열
private int capacity; //용량 크기
private int front; //맨 앞위 요소위치
private int rear; //맨 뒤의 요소 뒷칸 위치
private int num; //현재 데이터 개수
//실행시 예외: 비어잇음
public class EmptyIntQueueException extends RuntimeException{
public EmptyIntQueueException(){}
}
//실행시 예외: 가득 참
public class OverflowIntQueueException extends RuntimeException{
public OverflowIntQueueException(){}
}
//생성자
public IntQueue(int maxlen) {
num = front = rear = 0;
capacity = maxlen;
try {
que = new int[capacity];
} catch (OutOfMemoryError error) {
capacity = 0;
}
}
//인큐
public int enque(int x) throws OverflowIntQueueException{
if (num >= capacity)
throw new OverflowIntQueueException(); //큐가 가득참
que[rear++] = x;
num++;
if(rear == capacity)
rear = 0;
return x;
}
//디큐
public int deque() throws EmptyIntQueueException{
if(num <= 0)
throw new EmptyIntQueueException();
int x = que[front++];
num--;
if(front == capacity)
front = 0;
return x;
}
//피크
public int peek() throws EmptyIntQueueException{
if(num<=0)
throw new EmptyIntQueueException();
return que[front];
}
//비우기
public void clear(){
num = front = rear = 0;
}
//검색
public int indexOf(int x) {
for (int i = 0; i < num; i++) {
int idx = (i + front)%capacity;
if(que[idx] == x)
return idx;
}
return -1;
}
//용량
public int getCapacity() {
return capacity;
}
//현재 데이터 용량
public int size(){
return num;
}
public boolean isEmpty() {
return num <= 0;
}
public boolean isFull(){
return num >= capacity;
}
//front -> rear 순서로 출력
public void dump(){
if (num <= 0) {
System.out.println("큐가 비어있습니다.");
}else{
for (int i = 0; i < num; i++) {
System.out.println(que[(i+front)%capacity]+" ");
System.out.println();
}
}
}
}