队列特点:先进先出fifo(first in first out),在表的后端插入,在表的前端删除,类似排队进园区的队列
常见操作:enqueue;dequeue;front;isEmpty;size;clear;
以下代码
class QueueElement {
constructor(element, priority) {
this.element = element
this.priority = priority
}
}
class Queue {
constructor() {
this.items = []
this.length = 0
}
enqueue(element, priority) {
let queueElement = new QueueElement(element, priority)
if (this.length == 0) {
this.items.push(queueElement)
this.length += 1
} else {
let addFlag = false
for (let i = 0; i < this.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i,0,queueElement)
addFlag = true
this.length += 1
break
}
}
if (!addFlag) {
this.items.push(queueElement)
this.length += 1
}
}
};
dequeue() {
if (this.length == 0) { return false }
return this.items.shift()
};
front() {//返回队列中的第一个元素
if (this.length == 0) return false
return this.items[0]
};
isEmpty() {
return this.length === 0
};
size() {
return this.length
};
clear() {
this.items = []
this.length = 0
};
}
let queue = new Queue()
queue.enqueue("4", 400)
queue.enqueue("5", 500)
queue.enqueue("3", 300)
queue.enqueue("7", 700)
queue.enqueue("2", 200)
queue.enqueue("9", 900)
console.log(queue)
queue.dequeue()
console.log('de',queue)
console.log(queue.front())
console.log(queue.isEmpty())
console.log(queue.size())
queue.clear()
console.log(queue)