/**
* 力扣622.设计循环队列
*/
public class MyCircularQueue {
int[] elements;
// 队头
int front = 0;
// 元素个数
int size = 0;
// 数组容量
int capacity;
public MyCircularQueue(int k) {
elements = new int[k];
capacity = k;
}
// 索引的映射函数
private int index(int index) {
index += front;
return index - (index >= capacity ? capacity : 0);
// return (front + index) % capacity;
}
public boolean enQueue(int value) {
if (size == capacity) return false;
elements[index(size)] = value;
size ++;
return true;
}
public boolean deQueue() {
if (size == 0) return false;
front = index(1);
size --;
return true;
}
public int Front() {
if (size == 0) return -1;
return elements[front];
}
public int Rear() {
if (size == 0) return -1;
return elements[index(size - 1)];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}
数据结构之手写循环队列,数组模拟,力扣622.设计循环队列【Java】
于 2022-08-02 13:08:36 首次发布