循环队列简单实现
leetcode 622. 设计循环队列
class MyCircularQueue {
private int[] queue;
private int head;
private int tail;
private boolean isEmpty;
public MyCircularQueue(int k) {
queue = new int[k];
head = 0;
tail = 0;
isEmpty = true;
}
/**
* 1、若为满,则返回false
* 2、将tail设置为value,将tail往右移动
* 3、判断tail是否超过数组长度,若超过则将tail设置为0
* 4、enQueue成功时,需要将isEmpty属性修改为false
*/
public boolean enQueue(int value) {
if (isFull()) {
return false;
}
queue[tail] = value;
tail++;
if (tail == queue.length) {
tail = 0;
}
isEmpty = false;
return true;
}
/**
* 1、若为空,则返回false
* 2、获取head位置的值,将head往右移动
* 3、若head超过数组长度,则将head设置为0
* 4、判断head和tail是否重合,若重合则说明队列为空,修改isEmpty属性
*/
public boolean deQueue() {
if (isEmpty()) {
return false;
}
int v = queue[head];
head++;
if (head == queue.length) {
head = 0;
}
if (head == tail) {
isEmpty = true;
}
return true;
}
public int Front() {
if (isEmpty()) {
return -1;
}
return queue[head];
}
public int Rear() {
if (isEmpty()) {
return -1;
}
if (tail == 0) {
return queue[queue.length - 1];
}else {
return queue[tail - 1];
}
}
public boolean isEmpty() {
return isEmpty;
}
public boolean isFull() {
// 头和尾重合,并且队列不为空,则为full
return head == tail && (!isEmpty);
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/

浙公网安备 33010602011771号