JavaScript 基础数据结构与算法之队列封装

讲述前端开发必备的数据结构和算法基础

以下呈现了两种队列的封装方式  以及各自区别和差异

1、数组方式

首先用初始化item为 空数组的方式 进行封装

class Queue {
  // constructor() {
  //     this.items = []
  // }   初始化一个元素的话也可以直接跳出 constructor 很自由放在外面
  #items = []


  dequeue() { //出队 
    return this.#items.shift()  //删除队头
  }


  enqueue(data) { //进队  
    this.#items.push(data)
  }
  front() { //队头是谁  
    return this.#items.at(0)
  }
  
  isEmpty(){
    return this.#items.length===0
  }
  size(){
    return this.#items.length
  }
  clear(){
    this.#items = []
  }
  toString(){
    return this.#items.joim(" ")
  }
}
let queue = new Queue()

运行以后 我们在控制台进行操作

 首先看查是否为空  结果为true、size长度为0、enqueue进队分别加入猫和xiaoming 

front()看查队头为"猫"     dequeue出队"猫"  此时在看查队头为xiaoming

上述数组封装队的方式效率较低  因为每次shift()数组的数据都需要向前补齐 如果数据过多每次删除队头都需要所有数据向前移动  为了解决这个问题我们用对象的方式封装

2、对象的方式封装队列

class Queue {
    #items = {}  //一个对象
    #count = 0
    #lowCount = 0

    dequeue() { //出队列
        if(this.isEmpty()){
            return undefined
        } //防止空对象 删空的队头lowCount也++
        let res = this.#items[this.#lowCount]
        delete this.#items[this.#lowCount]
        this.#lowCount++
        return res
    }

    enqueue(data) {  //进入队列
        this.#items[this.#count] = data
        this.#count++  //别忘了加加
    }

    front() {  //返回对头 
        return this.#items[this.#lowCount]
    }

    isEmpty() {
        return this.size() === 0    
    }//调用下面的size() 看查返回值是否为0 

    size() { //长度的话就两个一减就行了  size就只是表示长度
        return this.#count-this.#lowCount
    }

    clear() {
        this.#items = {}
        this.#count = 0;
        this.#lowCount = 0
      //清除的时候都变为0  就行了
    }

    toString() {
        let str = ""
        for(let i =this.#lowCount;i<this.#count;i++){
            str += `${this.#items[i]} `
            }
        return str
    }
}
let queue = new Queue()

上述方式  虽然封装是略微复杂 但是大大提高了进出队列的效率,操作方式不变,原来shift虽然简单 但是会导致数组性能下降

下期更新封装队列的一些实际运用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃掉一直猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值