1οΈβ£ Circular Queue(μν ν)μ μ€κ° μ§μ μ°ΎκΈ°.
Javaμμ λ°°μ΄μ μ¬μ©νμ¬ κ΅¬νν μν νμμ μ€κ° μ§μ μ μ°Ύλ λ°©λ²μ νμ μμ μμΉ(βfrontβ)μ λ μμΉ(βrearβ)λ₯Ό κΈ°μ€μΌλ‘ κ³μ°ν μ μμ΅λλ€.
μ€κ° μ§μ μ μ°Ύλ 곡μμ μν νμ νΉμ±μ κ³ λ €νμ¬ μ μ ν μ‘°μ λμ΄μΌ ν©λλ€.
2οΈβ£ μ€κ° μ§μ μ μ°ΎκΈ° μν λ°©λ².
1οΈβ£ μ€κ° μ§μ κ³μ° 곡μ.
μ€κ° μ§μ μ μ°Ύλ λ°©λ²μ νμ μμμ κ³Ό λμ μ μ΄μ©νμ¬ κ³μ°ν μ μμ΅λλ€.
μν νμ ν¬κΈ°, μμ μΈλ±μ€(front), λ μΈλ±μ€(rear)λ₯Ό μ¬μ©νμ¬ μ€κ° μΈλ±μ€λ₯Ό κ³μ°ν μ μμ΅λλ€.
μ΄λ μ€κ° μ§μ μ κ³μ°νλ 곡μμ λ€μκ³Ό κ°μ΅λλ€.
(front + size / 2) % capacity
μ¬κΈ°μ βsizeβ λ νμ νμ¬ μ μ₯λ μμμ μμ΄κ³ , βcapacityβ λ νμ μ 체 ν¬κΈ°μ λλ€.
3οΈβ£ μμ
public class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;
public CircularQueue(int capacity) {
this.capacity = capacity;
this.queue = new int[capacity];
this.front = 0;
this.rear = 0;
this.size = 0;
}
public boolean isFull() {
return size == capacity;
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(int data) {
if (isFull()) {
throw new RuntimeException("Queue is full");
}
queue[rear] = data;
rear = (rear + 1) % capacity;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
int data = queue[front];
front = (front + 1) % capacity;
size--;
return data;
}
public int getMiddle() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
int middleIndex = (front + size / 2) % capacity;
return queue[middleIndex];
}
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(5);
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
cq.enqueue(50);
System.out.println("Middle element: " + cq.getMiddle()); // Output: Middle element: 30
cq.dequeue();
cq.enqueue(60);
System.out.println("Middle element: " + cq.getMiddle()); // Output: Middle element: 40
}
}
μ΄ μ½λμμλ βCircularQueueβ ν΄λμ€λ₯Ό μ μνκ³ , βenqueueβ, βdequeueβ, βisFullβ, βisEmptyβ λ©μλλ₯Ό ν¬ν¨ν©λλ€.
λν, νμ μ€κ° μμλ₯Ό λ°ννλ βgetMiddleβ λ©μλλ₯Ό μ μν©λλ€.
μ΄ λ©μλλ νμ¬ νμ ν¬κΈ°μ μμ μΈλ±μ€λ₯Ό μ¬μ©νμ¬ μ€κ° μΈλ±μ€λ₯Ό κ³μ°ν ν ν΄λΉ μΈλ±μ€μ μμλ₯Ό λ°νν©λλ€.