본문 바로가기

전공/자료구조와 실습

Queue) Circular Queue

728x90
반응형

Circular Queue

  • 선형 큐에서 요소를 추가하고 제거하는 과정에서 생기는 앞 공간을 재사용할 수 없는 문제가 있음
  • 이런 문제점을 해결하기 위해 고안됨
  • 시작 인덱스와 끝 인덱스가 만나서 순환함
  • Modulo Operation

Circular Queue 구현

  • front = (front + 1) % SIZE;
  • rear = (rear + 1) % SIZE;
public class CircularQueue {
    private int[] circularQueue;
    private int front;
    private int rear;
    private int size;

    public CircularQueue(int size) {
        this.size = size;
        circularQueue = new int[size];
        front = -1;
        rear = -1;
    }

    public boolean isFull() {
        return (rear + 1) % size == front;
    }

    public boolean isEmpty() {
        return front == -1;
    }

    public void enqueue(int data) {
        if (isFull()) {
            System.out.println("Queue is full!");
            return;
        }
        if (front == -1) front = 0;
        rear = (rear + 1) % size;
        circularQueue[rear] = data;
    }

    public int dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty!");
            return Integer.MIN_VALUE;
        }
        int data = circularQueue[front];
        if (front == rear) {
            front = -1;
            rear = -1;
        } else {
            front = (front + 1) % size;
        }
        return data;
    }
}
728x90
반응형

'전공 > 자료구조와 실습' 카테고리의 다른 글

Stack) Stack  (0) 2024.01.05
Queue) Priority Queue  (1) 2024.01.03
Queue) Queue란?  (0) 2024.01.03
Set) Hash set  (2) 2024.01.02
Map) HashMap  (1) 2024.01.02