队列

描述

队列是遵循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']

你可能感兴趣的:(队列)