Queue(队列)

/* 队列 */

class Queue {
    constructor() {
        this.count = 0
        this.lowestCount = 0
        this.items = {}
    }
    /* 向队列添加元素 */
    enqueue(element) {
        this.items[this.count] = element
        this.count++
    }
    /* 从队列移除元素 */
    dequeue() {
        if (this.isEmpty()) {
            return undefined
        }
        const result = this.items[this.lowestCount]
        delete this.items[this.lowestCount]
        this.lowestCount++
        return result
    }
    /* 查看队头元素 */
    peek() {
        if (this.isEmpty()) {
            return undefined
        }
        return this.items[this.lowestCount]
    }
    /* 检查队列是否为空 */
    isEmpty() {
        return this.count - this.lowestCount === 0
    }
    /* 获取队列的长度 */
    size() {
        return this.count - this.lowestCount
    }
    /* 清空队列 */
    clear() {
        this.items = {}
        this.count = 0
        this.lowestCount = 0
    }
}


/* 双端队列 */

class Deque {
    constructor() {
        this.count = 0
        this.lowestCount = 0
        this.items = {}
    }
    /* 检查队列是否为空 */
    isEmpty() {
        return this.count - this.lowestCount === 0
    }
    /* 获取队列的长度 */
    size() {
        return this.count - this.lowestCount
    }
    /* 清空队列 */
    clear() {
        this.items = {}
        this.count = 0
        this.lowestCount = 0
    }
    /* 在双端队列前端添加新的元素 */
    addFront(element) {
        if (this.isEmpty()) {
            this.addBack(element)
        } else if (this.lowestCount > 0) {
            this.lowestCount--
            this.items[this.lowestCount] = element
        } else {
            for (let i = this.count; i > 0; i--) {
                this.items[i] = this.items[i - 1]
            }
            this.count++
            this.lowestCount = 0
            this.items[0] = element
        }
    }
    /* 在双端队列后端添加新的元素 */
    addBack(element) {
        this.items[this.count] = element
        this.count++
    }
    /* 移除双端队列前端的元素 */
    removeFront() {
        if (this.isEmpty()) {
            return undefined
        }
        const result = this.items[this.lowestCount]
        delete this.items[this.lowestCount]
        this.lowestCount++
        return result
    }
    /* 移除双端队列后端的元素 */
    removeBack() {
        if (this.isEmpty()) {
            return undefined
        }
        this.count--
        const result = this.items[this.count]
        delete this.items[this.count]
        return result
    }
    peekFront() {
        if (this.isEmpty()) {
            return undefined
        }
        return this.items[this.lowestCount]
    }
    peekBack() {
        if (this.isEmpty()) {
            return undefined
        }
        return this.items[this.count - 1]
    }
}
上一篇:Delphi CheckListBox用法 文章来源于《傻猫网络日志》 https://www.samool.com/41856.html


下一篇:数据结构与算法 2.栈 Stack