一、认识队列结构
队列(Queue)一种受限的线性表
,先进先出
(FIFO)
- 受限之处在于它只允许在表的
前端
(front)进行删除操作,而在表的后端
(rear)进行插入操作
二、队列的封装
有两种实现方式,
- 基于数组实现
- 基于链表实现
我们先基于数组实现,后面学习到链表时,再进行学习
function Queue(){
this.items = []
// 向队尾添加一个或者多个新的项
Queue.prototype.enterqueue = function(element){
this.items.push(element)
}
// 移除队列第一项,并返回被移除的项
Queue.prototype.delqueue = function(){
if(!this.items.length) return false
return this.items.shift()
}
// 返回队列第一项
Queue.prototype.front = function(){
if(!this.items.length) return false
return this.items[0]
}
// 判断队列是否为空
Queue.prototype.isEmpty = function(){
return this.items.length === 0
}
// 返回队列内个数
Queue.prototype.size = function(){
return this.items.length
}
// toString
Queue.prototype.toString = function(){
this.items.length ? this.items.toString():''
}
}
// 队列的使用
const S = new Queue()
三、优先级队列
特点:
- 普通的队列插入一个元素,数据会被放在后端
- 但是优先级队列,在插入一个元素的时候会考虑
该数据的优先级
,和其他数据优先级进行比较,插入到正确的位置
四、优先级队列的封装
function PriorityQueue(){
const items = []
// 封装一个新的构造函数,用于保存元素和元素的优先级
function QueueElement(element, priority){
this.element = element
this.priority = proority
}
PriorityQueue.prototype.enterqueue = function(element, priority){
const qEl = new QueueElement(element,priority)
if(this.items.length === 0){
items.push(qEl)
}else{
let added = false
for(let i = 0; i<this.items.length; i++){
if(qEl.priority>this.items[i].priority){
this.items.splice(i,0,qEl)
added = true
break
}
}
if(!added){
items.push(qEl)
}
}
}
// 移除队列第一项,并返回被移除的项
PriorityQueue.prototype.delqueue = function(){
if(!this.items.length) return false
return this.items.shift()
}
// 返回队列第一项
PriorityQueue.prototype.front = function(){
if(!this.items.length) return false
return this.items[0]
}
// 判断队列是否为空
PriorityQueue.prototype.isEmpty = function(){
return this.items.length === 0
}
// 返回队列内个数
PriorityQueue.prototype.size = function(){
return this.items.length
}
// toString
PriorityQueue.prototype.toString = function(){
this.items.length ? this.items.toString():''
}
}