class LoopQueue {
constructor(capacity) {
this.data = [];
this.data.length = capacity;
this.front = 0;
this.tail = 0;
this.size = 0;
}
getSize() {
return this.size;
}
getCapacity() {
return this.data.length;
}
isEmpty() {
return this.size == 0;
}
enqueue(e) {
if (this.size == this.data.length) {
this.resize(this.getCapacity() * 2);
}
if (this.tail >= this.data.length && this.front >= 1 && this.size < this.data.length) {
this.tail = this.tail - this.data.length;
}
this.data[this.tail] = e;
this.tail = (this.tail + 1) % (this.data.length + 1);
this.size++;
}
dequeue() {
if (this.isEmpty()) {
throw Error('Cannot dequeue from an empty queue.');
}
if (this.front >= this.data.length && this.tail <= this.front && this.size < this.data.length) {
this.front = this.front - this.data.length;
}
let ret = this.data[this.front];
this.data[this.front] = undefined;
this.front = (this.front + 1) % (this.data.length + 1);
this.size--;
return ret;
}
getFront() {
if (this.isEmpty()) {
throw Error('Cannot dequeue from an empty queue.');
}
return this.data[this.front];
}
//如果队列的容量达到最大值要重新调整大小
resize(newCopacity) {
let newData = [];
newData.length = newCopacity;
for (let i = 0; i < this.data.length; i++) {
newData[i] = this.dequeue();
}
this.front = 0;
this.tail = this.size = this.data.length;
this.data = newData;
}
toString() {
console.log("front ", this.front, " tail ", this.tail, " ", this.data, " length ", this.data.length, " size ", this.size);
}
}
let loopQueue = new LoopQueue(5);
for (let i = 0; i < 100; i++) {
let isD = Math.random()*10;
if(isD > 5 && !loopQueue.isEmpty()){
loopQueue.dequeue();
}else{
loopQueue.enqueue(Math.ceil(Math.random()*10))
}
}
loopQueue.toString();