【数据结构】队列

队列: 受限的线性结构 先进先出 First In First Out

class Queue {
    constructor() {
        this.item = [];
    }
    // 入队
    enQueue(element) {
        this.item.push(element);
    }
    // 出队
    deQueue() {
        return this.item.shift();
    }
    // 返回队首
    front() {
        return this.item[0];
    }
    // 判空
    isEmpty() {
        if (!this.item.length) {
            return true;
        }
        return false;
    }
    // 大小
    size() {
        return this.item.length;
    }
}

优先级队列: 队列元素含有优先级,根据优先级入队 只有入队与普通队列不同,其余一致

// 用于存储数据和优先级
class QueueElement {
    constructor(element, priority) {
        this.element = element;
        this.priority = priority;
    }
}
// 值 priority
class PriorityQueue {
    constructor() {
        this.item = [];
    }
    // 入队
    enQueue(element, priority) {
        let queueElement = new QueueElement(element, priority);
        if (this.isEmpty()) {
            this.item.push(queueElement);
        } else {
            let length = this.size();
            // 判定是否在循环中将元素添加到队列
            let isAdd = false;
            for (let i = 0; i < length; i++) {
                let priority = this.item[i].priority;
                if (queueElement.priority < priority) {
                    // 在i位置插入一个元素,原来i位置及以后的元素依次后移一位
                    this.item.splice(i, 0, queueElement);
                    // 已添加改为true
                    isAdd = true;
                    return;
                }
            }
            // 未添加则添加至末尾
            if (!isAdd) {
                this.item.push(queueElement)
            }
        }
    }
}

优先级队列一般应用于线程队列,银行排队等场景

 

posted @ 2019-11-04 15:32  追僧逐月  阅读(114)  评论(0编辑  收藏  举报