https://leetcode.com/problems/design-circular-queue/
- Queue
- Design
Use an array with front, rear, and size to implement a circular queue.
O(1) per operation
O(k)
class MyCircularQueue {
private int[] arr;
private int front = 0, size = 0;
public MyCircularQueue(int k) {
arr = new int[k];
}
public boolean enQueue(int value) {
if (isFull()) return false;
arr[(front + size) % arr.length] = value;
size++;
return true;
}
public boolean deQueue() {
if (isEmpty()) return false;
front = (front + 1) % arr.length;
size--;
return true;
}
public int Front() {
return isEmpty() ? -1 : arr[front];
}
public int Rear() {
return isEmpty() ? -1 : arr[(front + size - 1 + arr.length) % arr.length];
}
public boolean isEmpty() { return size == 0; }
public boolean isFull() { return size == arr.length; }
}