一、什么是循环队列?
在数据出列时,将头指针往后移一位,当尾部指针到了链表长度时,那么会从0开始。
二、为什么是循环队列?
队列是一种先进先出的数据结构,那么当一个数据出列的时候有两种结果,
1.不管出列的数据,每次都往后移一位。消耗巨大内存。
2.队列里的每一个数据都会往前移一位,操作复杂,且耗时。
这时候有了循环队列,那么就可以避免链表当数据出列是空出的位置,也不用一个一个往前移动。
三、怎么实现循环?
主要的逻辑:
queue: 用数组实现的队列
rear: 尾部指针
font: 头部指针
maxlength:最大长度
size:当前数量
isFull() maxlength === size
isEmpty() size === 0
enqueue() 入队时判断满了就返回false,如果是isEmpty那么从0开始, 如果不是空的,那么放入rear+1的位置,且要判断rear是不是已经是maxlength - 1,是maxlength-1,那么rear=0, 最后size++
dequeue() 出队时判断空的就返回false,不是空的,且长度还没到maxlength-1,那么font++,size--;如果到了最末尾那么font=0 ,size--;
/**
* @param {number} k
*/
var MyCircularQueue = function(k) {
this.queue = new Array(k);
this.font = -1;
this.rear = -1;
this.size = 0;
this.maxLength = k
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if(this.isFull()){
return false;
}
if(this.isEmpty()){
this.queue[0] = value;
this.font = 0
this.rear = 0
}else{
if(this.rear !== this.maxLength - 1){
this.queue[this.rear + 1] = value
this.rear++
}else{
this.queue[0] = value
this.rear = 0
}
}
this.size++
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if(this.isEmpty()){
return false;
} else{
if(this.font !== this.maxLength - 1){
this.font++
}else{
this.font = 0
}
this.size--
return true
}
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
if(this.isEmpty()){
return -1
}
return this.queue[this.font]
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
if(this.isEmpty()){
return -1
}
return this.queue[this.rear]
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return this.size === 0
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return this.size === this.maxLength
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* var obj = new MyCircularQueue(k)
* var param_1 = obj.enQueue(value)
* var param_2 = obj.deQueue()
* var param_3 = obj.Front()
* var param_4 = obj.Rear()
* var param_5 = obj.isEmpty()
* var param_6 = obj.isFull()
*/