JavaScript如何创建队列

239 阅读1分钟

和栈一样,队列也是一种特殊的数组,其特点是先进先出

队列和栈十分相似,其主要区别在于添加和删除的方法,这是先进先出和后进先出不同造成的

    //这里面需要三个重要部分
//1. 长度
//2. 追踪队列头部元素
//3. 储存队列
class Queue {
    this.count = 0;
    //用来追踪被删除的元素,当lowestcount - count = 0时,队列为空.
    this.lowestCount = 0;
    this.items = ();

    //向队列添加元素
    enqueue(element)
    {
        this.items[this.count] = element;
        this.count++;
    }

    //从队列移除元素
    dequeue()
    {
        if(this.isEmpty())
        {
            return undefined;
        }

        //1. 暂存队列头部的值,以便删除后仍旧可以返回
        //2. 将lowestCount属性+1

        //因为将元素删除后,仍旧会占用索引位置(?),队列的头部位置以lowestCount为准

        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];
    }
    

    //检查队列是否为空并获取长度
    isEmpty()
    {
        return this.lowestcount - this.count === 0;
    }

    size()
    {
        return this.lowestcount - this.count;
    }

    //同时也可以这样写isEmpty()
    isEmpty()
    {
        return size() === 0;
    }


    //清空队列
    clear()
    {
        this.count = 0;
        this.lowestCount = 0;
        this.items = {};
    }


    //创建toString方法
    toString()
    {
        if(this.isEmpty())
        {
            return '';
        }

        let a = '${this.items[this.lowestCount]}';

        for(let i = this.lowestCount + 1;i < this.count;i++ )
        {
            a = '${a}','${this.items[i]}';
        }
        return a;
    }

}
本文借鉴于"学习JavaScript数据结构与算法"