循环队列
class Queue {
constructor(size = 100) {
this.size = size;
this.queue = new Array(size);
this.rear = 0;
this.front = 0;
}
push(val) {
if (!this.isFilled()) {
this.rear = (this.rear + 1) % this.size;
this.queue[this.rear] = val;
} else {
throw new Error('queue is filled.');
}
}
pop() {
if (!this.isEmpty()) {
this.front = (this.front + 1) % this.size;
return this.queue[this.front];
} else {
throw new Error('queue is empty.');
}
}
isEmpty() {
return this.rear === this.front;
}
isFilled() {
return (this.rear + 1) % this.size === this.front;
}
}
const q = new Queue(5);
for (let i = 0; i < 4; i++) {
q.push(i);
}
console.log(q);
console.log(q.isFilled());
console.log(q.pop());
q.push(4);
console.log(q);