코딩테스트
QueueArray
NellKiM
2025. 4. 10. 12:35
import java.util.Arrays;
public class QueueArray {
//1차원 배열을 사용하여 큐를 표현, 큐는 대기열을 의미!!
private int[] queue; //대기열
private int front, rear, size; //맨앞idx, 맨뒤idx, 전체 데이터 수
public QueueArray(int capacity) {//capacity:배열의 크기
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
//데이터 저장
public void enqueue(int value) {
if(size == queue.length) {//ArrayIndexOutOfBoundsException에 대한 처리
System.out.println("큐 오버플로우!"); //한개이상의 데이터를 삭제(조회) 후에 입력해야 함!!
return;
}
// rear++;//계속 증가하여 ArrayIndexOutOfBoundsException발생!!
rear = (rear+1)% queue.length;
queue[rear]=value;//핵심코드
size++;//전체 데이터 수 증가
}
//데이터 삭제와 조회
public int dequeue() {
if(size == 0) {//enqueue를 한번도 실행하지 않았을때의 처리
System.out.println("큐 언더플로우!"); //한개이상의 데이터를 삭제(조회) 후에 입력해야 함!!
return -1; //출력(삭제)할 데이터없음
}
int value = queue[front]; //큐이기 때문에 맨앞에 입력된 데이터 가져오기 ==> front사용!
// front++; //그다음 데이터를 얻기 위하여
//front를 계속 증가하여 ArrayIndexOutOfBoundsException발생!!
front = (front+1)% queue.length; //배열 인덱스 바운더리 내에서 로테이션 돌자!! (예: length가 5인 경우=> 0~4)
size--; //전체 데이터 수 감소
return value;
}
//데이터 단순 조회
public int peek() {
if (size == 0) return -1;
return queue[front];
}
//큐의 빈상태 확인
public boolean isEmpty() {
return size == 0;
}
public static void main(String[] args) {
QueueArray queue = new QueueArray(5);
queue.enqueue(10);//데이터 추가
queue.enqueue(20);//데이터 추가
queue.enqueue(30);//데이터 추가
queue.enqueue(40);//데이터 추가
queue.enqueue(50);//데이터 추가
queue.enqueue(60);//데이터 추가
System.out.println("deque==>"+queue.dequeue());
System.out.println("deque==>"+queue.dequeue());
System.out.println("deque==>"+queue.dequeue());
// System.out.println("deque==>"+queue.dequeue());
// System.out.println("deque==>"+queue.dequeue());
// System.out.println("deque==>"+queue.dequeue());
queue.enqueue(70);//데이터 추가
System.out.println("peek==>"+queue.peek());
System.out.println("isEmpty==>"+queue.isEmpty());
System.out.println(Arrays.toString(queue.queue));
}
}