자료구조&알고리즘

[JAVA자료구조]배열로 구현한 큐

인생개발 이정환 2024. 8. 20. 21:08
public class Queue {
    private int[] queue;  // 큐를 저장할 배열
    private int front;    // 큐의 앞을 가리키는 인덱스
    private int rear;     // 큐의 뒤를 가리키는 인덱스
    private int size;     // 큐의 크기
    private int capacity; // 큐의 최대 크기

    // 생성자: 큐의 크기를 초기화합니다.
    public Queue(int capacity) {
        this.capacity = capacity;
        this.queue = new int[capacity];
        this.front = 0;
        this.rear = 0;
        this.size = 0;
    }

    // 큐가 비어 있는지 확인합니다.
    public boolean isEmpty() {
        return size == 0;
    }

    // 큐가 가득 찼는지 확인합니다.
    public boolean isFull() {
        return size == capacity;
    }

    // 큐의 뒤에 요소를 추가합니다.
    public void enqueue(int item) {
        if (isFull()) {
            System.out.println("Queue is full");
            return;
        }
        queue[rear] = item;
        rear = (rear + 1) % capacity; // 원형 큐를 위해 rear를 모듈로 연산합니다.
        size++;
    }

    // 큐의 앞에서 요소를 제거하고 반환합니다.
    public int dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return -1;
        }
        int item = queue[front];
        queue[front] = 0; // 제거된 자리를 0으로 설정 (필수는 아님)
        front = (front + 1) % capacity; // 원형 큐를 위해 front를 모듈로 연산합니다.
        size--;
        return item;
    }

    // 큐의 앞에 있는 요소를 반환하지만 제거하지는 않습니다.
    public int peek() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return -1;
        }
        return queue[front];
    }

    // 큐의 상태를 출력합니다.
    public void display() {
        System.out.print("Queue: ");
        for (int i = 0; i < capacity; i++) {
            System.out.print(queue[i] + " ");
        }
        System.out.println();
    }

    // 큐 사용 예시
    public static void main(String[] args) {
        Queue q = new Queue(5);
        q.enqueue(10);
        q.enqueue(20);
        q.enqueue(30);
        q.display();  // Queue: 10 20 30 0 0 

        System.out.println(q.dequeue());  // 10
        q.display();  // Queue: 0 20 30 0 0 

        System.out.println(q.peek());  // 20
        q.display();  // Queue: 0 20 30 0 0 
    }
}