队列-双端队列

/* 1.队列

队列是遵循先进先出(FIFO,也称为先来先服务)原则的一组有序的项。

队列在尾部添加新 元素,并从顶部移除元素。

最新添加的元素必须排在队列的末尾 */

复制代码
class Queue {
    constructor(){
        this.count = 0;
        this.lowestCount = 0; // 由于我们将要从队列前端移除元素,同样需要一个变量来帮助我们追踪第一个元素
        this.items = {};
    }
    // 向队列添加元素
    enqueue(element) {
        this.items[this.count] = element;
        this.count++;
    }
    // 检查队列是否为空并获取它的长度
    isEmpty() {
        return this.count - this.lowestCount === 0;
    }
    // 从队列移除元素
    dequeue() {
        if(this.isEmpty()){
            return undefined;
        }
        const result = this.items[this.lowestCount];
        delete this.items[this.lowestCount];
        this.lowestCount++;
        return result;
    }
    // 从队列移除元素
    peek() {
        if(this.isEmpty()){
            return undefined;
        }
        return this.items[this.lowestCount];
    }
    // 清空队列
    clear(){
        this.items = {};
        this.count = 0;
        this.lowestCount = 0;
    }
    // 创建 toString 方法
    /* 在 Stack 类中,我们从索引值为 0 开始迭代 items 中的值。由于 Queue 类中的第一个索引
        值不一定是 0,我们需要从索引值为 lowestCount 的位置开始迭代队列。    */
    toString() {
        if(this.isEmpty()){
            return '';
        }
        let objString = `${this.items[this.lowestCount]}`;
        for (let i = this.lowestCount + 1; i < this.count; i++) {
            objString = `${objString},${this.items[i]}`        
        }
    }
}
复制代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
双端队列(deque,或称 double-ended queue)是一种允许我们同时从前端和后端添加和移除
元素的特殊队列
 
由于双端队列同时遵守了先进先出和后进先出原
则,可以说它是把队列和栈相结合的一种数据结构。
 
既然双端队列是一种特殊的队列,我们可以看到其构造函数中的部分代码和队列相同,包括
相同的内部属性和以下方法:isEmpty、clear、size 和 toString。
*/
 
class Deque {
    constructor(){
        this.count = 0;
        this.lowestCount = 0;
        this.items = {};
    }
      // 检查队列是否为空并获取它的长度
      isEmpty() {
        return this.count - this.lowestCount === 0;
    }
        // 向队列添加元素
        addBack(element) {
            this.items[this.count] = element;
            this.count++;
        }
    // 向双端队列的前端添加元素
    addFront(element) {
        if(this.isEmpty()){
            this.addBack(element);
        } else if(this.lowestCount>0){
            this.lowestCount--;
            this.items[this.lowestCount] = element;
        } else{
            for (let i = this.count; i > 0; i--) { // {3}
                this.items[i] = this.items[i - 1];
            }
            this.count++;
            this.lowestCount = 0;
            this.items[0] = element; // {4}
        }
    }
}

  

posted @   小白咚  阅读(1518)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示