队列的实现 -- 数据结构与算法的javascript描述 第五章

队列也是列表的一种,有不同于列表的规则。

  1. 先进先出
  2. 入队方法
  3. 出队方法
  4. 可以找到队首
  5. 可以找到队尾
  6. 可以查看队列有多长
  7. 可以查看队列是否为空

这是一个基本的需求,围绕他来实现,当然我们可以自己扩展列表的规则并辅以代码实现

queue.js

/**
     * 队列,先进先出  First-In-First-Out
     * 入队  出队
     * @constructor
     */
    function Queue(){
        this.dataStore=[];
        this.count = length;
        this.clear = clear;
        this.enqueue = enqueue;
        this.dequeue = dequeue;
        this.front = front;
        this.back = back;
        this.toString = toString;
        this.empty = empty;

        /**
         * 队列数量
         * @returns {Number}
         */
        function length(){
            return this.dataStore.length;
        }

        /**
         * 清空队列
         */
        function clear(){
            this.dataStore = [];
        }

        /**
         * 查询队列是否为空
         * @returns {boolean}
         */
        function empty() {
            if (this.dataStore.length == 0) {
                return true;
            }
            else {
                return false;
            }
        }

        /**
         * 入列
         * @param element
         */
        function enqueue(element){
            this.dataStore.push(element)
        }

        /**
         * 出列
         * @returns {*}
         */
        function dequeue(){
            return this.dataStore.shift();
        }

        /**
         * 队尾
         * @returns {*}
         */
        function back() {
            return this.dataStore[this.dataStore.length-1];
        }

        /**
         * 队首
         * @returns {*}
         */
        function front(){
            return this.dataStore[0]
        }

        /**
         * 返回队列所有元素
         * @returns {string}
         */
        function toString(){
            var s = '';
            for(var i=0;i<this.dataStore.length;i++){
                s+= this.dataStore[i]+'
'
            }
            return s;
        }
    }

    window.Queue = Queue
原文地址:https://www.cnblogs.com/iyueyao/p/3979807.html