数据结构(双端队列的封装)

216 阅读1分钟

双端队列 :一种允许我们同时从前端和后端添加和移除元素的队列。

下面是我在学习队列的过程中,封装的双端队列数据结构

  // 双端队列
        class Deque {
            constructor() {
                this.item = {}
                this.count = 0
                this.first = 0
            }
            // 在队列前面添加 
            // 一共有三种情况
            // 第一种 : 队列为空的时候  直接调用addB()减少代码的重复
            // 第二种 : 队列删除过元素   此时应该先将记录第一个元素的变量减一 在添加元素
            // 第三种 :队列不为空,切队列在此之前没有删除过元素 此时需要将队列最原始的数据向后移动一个,然后在将元素添加在第一个位置
            addF(e) {
                if(this.isEmpty()) {
                    this.addB(e)
                }else if(this.first > 0) {
                    this.first--
                    this.item[this.first] = e
                }else {
                    for(let i = this.count;i>0;i--) {
                        this.item[i] = this.item[i-1]
                    }
                    this.count++
                    this.first = 0
                    this.item[0] = e
                }
            }
            addB(e) {
                this.item[this.count] = e 
                this.count ++
            }
            size() {
                return this.count - this.first
            }
            isEmpty() {
                return this.count - this.first === 0
            }
            removeF() {
                if(this.isEmpty()) {
                    return undefined
                }
                let res = this.item[this.first]
                delete this.item[this.first]
                this.first ++
                return res
            }
            removeB() {
                if(this.isEmpty()) {
                    return undefined
                }else {
                    this.count--
                    let res = this.item[this.count]
                    delete this.item[this.count]
                    return res
                }
            }
        }

        
        var a = new Deque()
        console.log(a);
        a.addB('a')
        a.addB('b')
        a.addB('c')
        a.addF('d')
        a.removeF()
        console.log(a.item);

这只是简单的封装了一个双端队列数据结构,这里我使用的是对象的方法来保存队列中的数据,也可以使用数组来封装。 参考书籍:《学习JacaScript数据结构与算法》(第三版)