JS队列的一种实现方式

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();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值