概念
队列是遵循FIFO(First In First Out,先进先出 ) 原则的一组有序的项。
队列在尾部添加新元素,并从顶部移除元素。
最新添加的元素必须排在队列的末尾。
创建队列
实现方法
用数组模拟队列,数组中有shift()从头部推出,和push()从尾部推入的方法
从数据结构方面来讲,要实现一个数据结构的方法,无非就是CRUL,
-
增—尾部增加,头部增加,中间某个位置增加
enqueue(element(s)):向队列尾部添加一个(或多个)新的项。 -
删—删除某个数据
dequeue():移除队列的第一(即排在队列最前面的)项,并返回被移除的元素。
查—查找某个数据的位置,查找数据是否为空
front():返回队列中第一个元素——最先被添加,也将是最先被移除的元素。队列不做任何变动(不移除元素,只返回元素信息——与Stack类的peek方法非常类似)。
isEmpty():如果队列中不包含任何元素,返回true,否则返回false。 size():返回队列包含的元素个数,与数组的length属性类似。
改—改变整个数据置空,改变单个数据
function Queue() {
items = []
this.enqueue = function (element) {
items.push(element)
}
// 出队
this.dequeue = function () {
return items.shift()
}
// 道队列最前面的项是什么
this.front = function () {
return items[0]
}
this.isEmpty = function () {
return items.length === 0
}
this.size = function () {
return items.length
}
this.print = function () {
console.log(items.toString())
}
}
var queue = new Queue()
console.log(queue.isEmpty())
变种
优先队列
实现一个优先队列
有两种选项:
- 设置优先级,然后在正确的位置添加元素;
- 用入列操作添加元素,然后按照优先级移除它们。
最小优先队列,,因为优先级的值较小的元素被放置在队列最前面
思路🤔
- 确定数据数据结构[{element,priority}…],priority优先
- 执行插入
2-1. if为空,直接插入
2-2. else,遍历整个数组,插入优先级更低的之前,如果没有找到,插入到队伍最后
function PriorityQueue() {
var items = []
function QueueElement(element, priority) {
// {1}
this.element = element
this.priority = priority
}
this.enqueue = function (element, priority) {
let queueElement = new QueueElement(element, priority)
if (this.isEmpty()) {
items.push(queueElement)
} else {
let added = false
for (let i = 0; i < items.length; i++) {
if (queueElement.priority < items[i].priority) {
items.splice(i, 0, queueElement) // {3}
added = true
break
}
}
if (!added) {
items.push(queueElement)
}
}
}
//其他方法和默认的Queue实现相同
// 出队
this.dequeue = function () {
return items.shift()
}
// 道队列最前面的项是什么
this.front = function () {
return items[0]
}
this.isEmpty = function () {
return items.length === 0
}
this.size = function () {
return items.length
}
this.print = function () {
console.log(items)
}
}
var priorityQueue = new PriorityQueue()
priorityQueue.enqueue('John', 2)
priorityQueue.enqueue('0000', 4)
priorityQueue.enqueue('Jack', 1)
priorityQueue.enqueue('0000', 0)
priorityQueue.enqueue('Camila', 1)
priorityQueue.print()