原理
固定长度的队列,队列满的情况下无法入队。通过为队列添加一个size属性,此属性为当前队列中元素的个数,size属性随入队和出队操作发生改变,根据size属性来确定头指针head和尾指针tail的序号。
show me the code
function circleQue(length) {
this.dataStore = [];
this.head = 0;
this.tail = 0;
this.size = 0;
this.length = length;
}
circleQue.prototype = {
isEmpty() {
return this.size === 0;
},
isFull() {
return this.size === this.length;
},
// 获取队首元素
front() {
if (this.isEmpty()) {
return null;
}
return this.dataStore[this.head];
},
// 获取队尾元素
rear() {
if (this.isEmpty()) {
return null;
}
return this.dataStore[this.tail === 0 ? this.length - 1 : this.tail - 1];
},
// 入队
enque(data) {
if (this.isFull()) {
return false;
}
this.size++;
this.dataStore[this.tail] = data;
this.tail = this.tail === this.length - 1 ? 0 : this.tail + 1;
return true;
},
// 出队
deque() {
if (this.isEmpty()) {
return null;
}
this.size--;
var res = this.dataStore[this.head];
this.head = this.head === this.length - 1 ? 0 : this.head + 1;
return res;
},
};
var cq = new circleQue(3);
cq.enque(1);
cq.enque(2);
cq.enque(3);
cq.enque(4);
cq.deque();
console.log(cq.front());
console.log(cq.rear());
cq.enque(5);
cq.enque(6);
console.log(cq.front());
console.log(cq.rear());