使用js封装数据类型---队列

一、队列的特点

先进先出,后进后出

二、使用类和数组封装单向队列

// 封装的栈数据类型
class Queue {
    // 私有属性
    #items = [];
    // 弹出队列
    dequeue() {
        return this.#items.shift();
    }
    // 进入队列
    enqueue(data) {
        this.#items.push(data);
    }
    // 获取队列元素
    front() {
        // return this.#items[0];
        return this.#items.at(0);
    }
    // 判断是否未空
    isEmpty() {
        return this.#items.length === 0;
    }
    // 栈的长度
    size() {
        return this.#items.length;
    }
    // 清空栈
    clear() {
        this.#items = [];
    }
    // 转换成字符串
    toString(data) {
        return this.#items.join(data);
    }
}

 三、使用类和对象封装的双向队列数据类型

// 封装的双向队列数据类型
class DeQueue {
    // 私有属性
    #items = {};
    #lowCount = 0;
    #count = 0;

    // 进入队列
    addBack(data) {
        this.#items[this.#count] = data;
        this.#count++;
    }
    addFront(data) {
        if (this.isEmpty()) {
            this.addBack(data);
        } else {
            if (this.#lowCount > 0) {
                this.#items[this.#lowCount - 1] = data;
                this.#lowCount--;
            } else {
                for (let i = this.#count; i > 0; i--) {
                    this.#items[i] = this.#items[i - 1];
                }
                this.#items[0] = data;
                this.#count++;
            }
        }
    }
    // 弹出队列
    removeFront() {
        if (this.isEmpty()) return
        let res = this.#items[this.#lowCount];
        delete this.#items[this.#lowCount];
        this.#lowCount++;
        return res;
    }
    removeBack() {
        if (this.isEmpty()) return
        this.#count--;
        let res = this.#items[this.#count];
        delete this.#items[this.#count];
        return res;
    }
    // 获取队列第一个元素
    peekFront() {
        return this.#items[this.#lowCount];
    }
    // 获取队列最后一个元素
    peekBack() {
        if (this.isEmpty()) return
        return this.#items[this.#count - 1];
    }
    // 判断是否未空
    isEmpty() {
        return this.size() === 0;
    }
    // 栈的长度
    size() {
        return this.#count - this.#lowCount;
    }
    // 清空栈
    clear() {
        this.#items = {}
        this.#count = 0;
        this.#lowCount = 0;
    }
    // 转换成字符串
    toString(data) {
        let str = '';
        for (let i = this.#lowCount; i < this.#count; i++) {
            str += this.#items[i] + data;
        }
        return str;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值