队列

作者: 林键燃 | 来源:发表于2019-03-08 15:35 被阅读0次

    描述

    队列是遵循FIFO(First In First Out,先进先出,也成为先来先服务)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。最新添加的元素必须排在队列的末尾

    实现

    /**
     * @description 使用 WeakMap 对象创建类的私有属性 
     */
    const Queue = (function() {
        const items = new WeakMap()
    
        class Queue {
            constructor() {
                items.set(this, [])
            }
            enqueue(element) {
                let q = items.get(this)
                q.push(element)
            }
            dequeue() {
                let q = items.get(this)
                return q.shift()
            }
            front() {
                let q = items.get(this)
                return q[0]
            }
            isEmpty() {
                let q = items.get(this)
                return q.length === 0
            }
            size() {
                return q.length
            }
            print() {
                console.log(items.get(this).toString())
            }
        }
    
        return Queue
    })()
    
    let q = new Queue()
    

    实例

    /**
     * @description 循环队列 --- 击鼓传花
     */
    const hotPotato = (nameList, num) => {
        if (nameList.length === 0 || num < 0) {
            return false
        }
        let eliminated = ''
        let queue = new Queue()
    
        nameList.forEach(i => {
            queue.enqueue(i)
        })
        while (queue.size() > 1) {
            for (let i = 0; i < num; i++) {
                queue.enqueue(queue.dequeue())
            }
            eliminated = queue.dequeue()
            console.log('eliminated: ' + eliminated)
        }
    
        return queue.dequeue()
    }
    
    let names = ['Jogn', 'Jack', 'Boo', 'Aranl', 'Queue']
    

    相关文章

      网友评论

          本文标题:队列

          本文链接:https://www.haomeiwen.com/subject/qzbrpqtx.html