力扣622(设计循环队列)
解题思路:
- 熟悉队列的结构特点(先进先出)
- 明白用数组实现循环队列的要素
- 如何实现循环(参照我的算法与数据结构专栏中认识栈和队列一文)
- 如何判断循环“数组”是否已满,同参照。
class MyCircularQueue {
public int[] elem;
public int front;
public int rear;
public MyCircularQueue(int k) {
this.elem=new int[k+1];//因为采用的是牺牲一个位置的方法,所以还它一个位置
}
public boolean enQueue(int value) {
if(isFull()){
return false;
}
this.elem[rear]=value;
this.rear=(this.rear+1)%this.elem.length;
return true;
}
public boolean deQueue() {
if(isEmpty()){
return false;
}
this.front=(this.front+1)%this.elem.length;
return true;
}
public int Front() {
if(isEmpty()){
return -1;
}
return this.elem[front];
}
public int Rear() {
if(isEmpty()){
return -1;
}
int index=(rear-1+elem.length)%elem.length;
return this.elem[index];
}
public boolean isEmpty() {
return front==rear;//因为此种情况下,只有空才能true
}
public boolean isFull() {
//可以采用牺牲一个位置的判断方法,我们就可以少定义一个字段啦
int index=(rear+1)%elem.length;
return index==front;
}
}