题目描述
设计一个固定大小的队列,可以方便的利用队列的空间。
输入输出样例
MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
circularQueue.enQueue(1); // 返回 true
circularQueue.enQueue(2); // 返回 true
circularQueue.enQueue(3); // 返回 true
circularQueue.enQueue(4); // 返回 false,队列已满
circularQueue.Rear(); // 返回 3
circularQueue.isFull(); // 返回 true
circularQueue.deQueue(); // 返回 true
circularQueue.enQueue(4); // 返回 true
circularQueue.Rear(); // 返回 4
题解
四个变量:
- queue 数组,用于存储元素
- cap 数组初始化的尺寸
- head 指向队列的头
- tail 指向队列的尾
- size 队列中的元素个数
代码:
class MyCircularQueue {
int cap;
int[] queue;
int head; // 指向队列头
int tail; // 指向队列尾
int size = 0;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
if (k <= 0)
throw new IllegalArgumentException("非法的尺寸!");
this.cap = k;
queue = new int[cap];
head = 0;
tail = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
// 需要看看还有没有空间用来入队列
if(size == cap) {
System.out.println("队列满了");
return false;
}
// 在尾部添加元素
queue[tail] = value;
tail = (tail + 1) % cap;
size++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(size == 0) {
System.out.println("队列为空");
return false;
}
head = (head + 1) % cap;
size--;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if(size == 0) return -1;
return queue[head];
}
/** Get the last item from the queue. */
public int Rear() {
if(size == 0) return -1;
if(tail == 0) return queue[cap-1];
return queue[tail-1];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return size == 0;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return size == cap;
}
}