队列遵循先进先出原则
创建队列
首先我们需要创建自己的类, 来表示队列. 先从最基本的声明开始:
class Queue {
constructor() {
this.items = []
}
// 添加元素
enqueue = function(elem) {
this.items.push(elem)
}
// 返回被删除的元素
dequeue = function(){
if(this.empty()){
return 'this itmes is empty'
} else {
return this.items.shift()
}
}
// 返回队列中最先添加的元素
front = function(){
return this.items[0]
}
// 判断队列中是否包含元素
empty = function() {
return this.items.length > 0 ? false : true
}
// 返回队列包含的元素个数
size = function() {
return this.items.length
}
// 打印队列元素
print = function () {
console.log(this.items.toString())
}
}
let queue = new Queue()
queue.enqueue('a')
queue.enqueue('b')
queue.print()
优先队列
实现一个优先队列,有两种选项,设置优先级,然后在正确的位置添加元素; 或者用入列操作添加元素,然后按照优先级移除它们.
接下来我们看看它的实现
function PriorityQueue() {
let items = []
function QueueElement(elem,priority) {
this.elem = elem
this.priority = priority
}
this.enqueue = function(elem,priority) {
let queueElement = new QueueElement(elem,priority)
let added = false
for (let i = 0; i < items.length; i++) {
if(queueElement.priority < items[i].priority) {
items.splice(i,0,queueElement)
added = true
break;
}
}
if(!added) {
items.push(queueElement)
}
}
this.print = function () {
for (let i = 0; i < items.length; i++) {
console.log(`${items[i].elem} - ${items[i].priority}`)
}
}
}
let priorityQueue = new PriorityQueue()
priorityQueue.enqueue('John',2)
priorityQueue.enqueue('Jack',1)
priorityQueue.enqueue('Camila',1)
priorityQueue.print()
循环队列 --- 击鼓传❀
// 循环队列
function hotPotato(nameList,num) {
let queue = new Queue()
for (let i = 0; i < nameList.length; i++) {
queue.enqueue(nameList[i])
}
let eliminated = ''
while (queue.size() > 1) {
for (let i = 0; i < num; i++) {
queue.enqueue(queue.dequeue())
}
eliminated = queue.dequeue()
console.log(eliminated + 'out')
}
return queue.dequeue()
}
let names = ['a','b','c','d','e','f']
// b c d e f a
// c d e f a b
// d e f a b c
// e f a b c d
// f a b c d e
// a b c d e f
// b c d e f a b out
// 新数组 c d e f a
// d e f a c i = 0
// e f a c d i = 1
// f a c d e i = 2
// a c d e f i = 3
// c d e f a i = 4
// d e f a c i = 5
// e f a c d // i = 6 e out
let winner = hotPotato(names,7)
console.log(winner)