JavaScript實現一個隊列(Queue)


 

最簡單的隊列是數組Array。從前面取元素,從后面取元素,合並元素,分割元素等等都可以實現。

/**
 * 基於數組封裝隊列類
 *
 * @returns {*}
 * @constructor
 */
function Queue() {
    // 屬性
    this.items = []

    // 方法
    // 1.enqueue():將元素加入到隊列中
    Queue.prototype.enqueue = element => {
        this.items.push(element)
    }

    // 2.dequeue():從隊列中刪除前端元素
    Queue.prototype.dequeue = () => {
        return this.items.shift()
    }

    // 3.front():查看前端的元素
    Queue.prototype.front = () => {
        return this.items[0]
    }

    // 4.isEmpty:查看隊列是否為空
    Queue.prototype.isEmpty = () => {
        return this.items.length == 0;
    }

    // 5.size():查看隊列中元素的個數
    Queue.prototype.size = () => {
        return this.items.length
    }

    // 6.toString():將隊列中元素以字符串形式輸出
    Queue.prototype.toString = () => {
        let resultString = ''
        for (let i of this.items){
            resultString += i + ' '
        }
        return resultString
    }
}
/**
 * 封裝優先級隊列
 *
 * @returns {*}
 * @constructor
 */
function PriorityQueue() {

    //內部類:在類里面再封裝一個類;表示帶優先級的數據
    function QueueElement(element, priority) {
        this.element = element;
        this.priority = priority;
    }

    // 封裝屬性
    this.items = []

    // 1.實現按照優先級插入方法
    PriorityQueue.prototype.enqueue = (element, priority) => {
        // 1.1.創建QueueElement對象
        let queueElement = new QueueElement(element, priority)

        // 1.2.判斷隊列是否為空
        if(this.items.length == 0){
            this.items.push(queueElement)
        }else{
            // 定義一個變量記錄是否成功添加了新元素
            let added = false
            for(let i of this.items){
                // 讓新插入的元素與原有元素進行優先級比較(priority越小,優先級越大)
                if(queueElement.priority < i.priority){
                    this.items.splice(i, 0, queueElement)
                    added = true
                    // 新元素已經找到插入位置了可以使用break停止循環
                    break
                }
            }
            // 新元素沒有成功插入,就把它放在隊列的最前面
            if(!added){
                this.items.push(queueElement)
            }
        }
    }

    // 2.dequeue():從隊列中刪除前端元素
    PriorityQueue.prototype.dequeue = () => {
        return this.items.shift()
    }

    // 3.front():查看前端的元素
    PriorityQueue.prototype.front = () => {
        return this.items[0]
    }

    // 4.isEmpty():查看隊列是否為空
    PriorityQueue.prototype.isEmpty = () => {
        return this.items.length == 0;
    }

    // 5.size():查看隊列中元素的個數
    PriorityQueue.prototype.size = () => {
        return this.items.length
    }

    // 6.toString():以字符串形式輸出隊列中的元素
    PriorityQueue.prototype.toString = () => {
        let resultString = ''
        for (let i of this.items){
            resultString += i.element + '-' + i.priority + ' '
        }
        return resultString
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM