使用JavaScript浅谈队列

什么是队列?

队列可以看做是一个单向通道,先进去的元素,必定会先出来(不考虑优先级的情况下)FIFO first-in-first-out,队列的元素从队尾进入,从队头出来。

抽象队列的数据结构类型

size(属性):队列中的元素个数

dataSource(属性):队列中存储元素的数组

enqueue(方法):向队尾添加一个元素

dequeue(方法):删除队头元素

front(方法):读取队头元素

back(方法):读取队尾元素

length(方法):返回队列元素个数

clear(方法):清空队列

empty(方法):判断队列是否为空

toString(方法):显示所有的队列元素

有了队列的抽象数据结构类型,我们可以得到一下的队列类:

class Queue {
    constructor() {
        this.dataSource = [];
        this.size = 0;
    }
    // enqueue:向队列尾增加元素
    enqueue(element) {
        this.dataSource.push(element);
        this.size++;
    }
    // dequeue: 删除队头元素
    dequeue() {
        if (this.empty()) {
            this.size--;
            return this.dataSource.shift();
        }
    }
    // empty: 判断是否为空队列
    empty() {
        if (this.size > 0) {
            return true;
        }
        return false;
    }
    // front: 返回队头元素
    front() {
        if (this.empty()) {
            return this.dataSource[0];
        }
    }
    // back: 返回队尾元素
    back() {
        if (this.empty()) {
            return this.dataSource[this.size - 1];
        }
    }
    // length: 返回队列元素总数
    length() {
        return this.size;
    }
    // clear: 清空队列
    clear() {
        this.dataSource.length = 0;
        this.size = 0;
    }
    // toString: 返回队列所有元素
    toString() {
        return this.dataSource;
    }
}

有了这个基本的队列类,我们可以在上面进行扩展,去解决实际开发中所遇到的问题。

 源码和案例地址:https://gitee.com/mvc_ydb/data-structure/blob/master/queue.js

posted @ 2020-03-15 14:33  只会一点前端  阅读(719)  评论(0编辑  收藏  举报