题目
通过数组实现一个队列,队列是先进先出
- 通过两个指针,一个用来记录,一个用来弹出,再使用一个 size 变量来记录剩余空间大小,再额外使用一个 size 变量,可以省去通过两个指针计算剩余空间的多种情况,在空间满足的情况下,只管移动就行了,类似一个环形的 ring buffer
function Ring(maxLimit) {
this.pullIndex = 0;
this.popIndex = 0;
this.size = 0;
this.limit = maxLimit;
this.arr = [];
this.push = function (value) {
if (this.size === this.limit) {
return "out range";
}
this.size++;
arr[this.push] = value;
this.push = this.nextIndex(this.push);
};
this.pop = function () {
if (this.size === 0) {
return "no value stored";
}
this.size--;
const popValue = this.arr[this.popIndex];
this.popIndex = this.nextIndex(this.popIndex);
return popValue;
};
// 获取下一个位置
this.nextIndex = function (index) {
return index + 1 < this.limit ? index + 1 : 0;
};
}