1、队列的封装
function Queue() {
this.items = []
// 1.入队
Queue.prototype.enqueue = function (element) {
this.items.push(element)
}
// 2.出队
Queue.prototype.dequeue = function () {
this.items.shift()
}
// 3.查看前端元素
Queue.prototype.front = function () {
return this.items[0]
}
// 4.判断是否为空
Queue.prototype.isEmpty = function () {
return this.items.length === 0
}
// 5.获取元素个数
Queue.prototype.size = function () {
return this.items.length
}
// 6.toString方法
Queue.prototype.toString = function () {
let resultString = ''
for(let i = 0; i < this.items.length; i++){
resultString += this.items[i]
}
return resultString
}
}
2、优先级队列封装
内部封装队列元素类,包含元素和优先级属性,在入队操作时遍历判断元素优先级所处位置进行插入,其他操作和普通队列一致。
function PriorityQueue() {
this.items = []
function QueueElement(element, priority) {
this.element = element
this.priority = priority
}
PriorityQueue.prototype.enqueue = function (element, priority) {
let queueElement = new QueueElement(element, priority)
if(this.items.length === 0){
this.items.push(queueElement)
}else {
let flag = false
for (let i = 0; i < this.items.length; i++){
if (priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement)
flag = true
break
}
}
if (!flag){
this.items.push(queueElement)
}
}
}
// 2.出队
PriorityQueue.prototype.dequeue = function () {
this.items.shift()
}
// 3.查看前端元素
PriorityQueue.prototype.front = function () {
return this.items[0]
}
// 4.判断是否为空
PriorityQueue.prototype.isEmpty = function () {
return this.items.length === 0
}
// 5.获取元素个数
PriorityQueue.prototype.size = function () {
return this.items.length
}
// 6.toString方法
PriorityQueue.prototype.toString = function () {
let resultString = ''
for(let i = 0; i < this.items.length; i++){
resultString += this.items[i].element + '-' + this.items[i].priority + ' '
}
return resultString
}
}