JavaScript数据结构之队列
class Queue{
constructor() {
this.count = 0
this.list = {}
this.lowestCount=0
}
//往队列添加元素
enqueue (element) {
this.list[this.count] = element
this.count++
}
//检测队列是否为空
isEmpty () {
return this.count-this.lowestCount===0
}
//从队列里移除元素
dequeue () {
if (this.isEmpty()) {
return undefined
}
const result = this.list[this.lowestCount]
delete this.list[this.lowestCount]
this.lowestCount++
return result
}
//查看队列头元素
peek () {
if (this.isEmpty()) {
return undefined
}
return this.list[this.lowestCount]
}
//获取队列长度
size () {
return this.count - this.lowestCount
}
//清空队列
clear () {
this.list = {}
this.count = 0
this.lowestCount=0
}
//字符串方法
toString () {
if (this.isEmpty()) {
return ''
}
let str = `${this.list[this.lowestCount]}`
for (let i = this.lowestCount + 1; i < this.count; i++){
str+=`,${this.list[i]}`
}
return str
}
//
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。