昨天复现了栈,栈是先进后出,而队列遵从先进先出原则,就类似我们排队打饭,第一个到的一定是第一打饭走的,也像极了js代码正常的执行顺序,从上到下。
首先复现队列我第一个想到的就是数组,很方便,而且有现成的方法,但是为了让这次做的更有挑战性,也为了拥有更快的效率,我们这次采用其他方法。
首先我们先创造一个队列:
class Queue{
constructor(){
this.queue={}, //由queue记录队列列表
this.index=0, // index记录个数
this.top=0 //记录队列头部id
}
}
然后我们来条论队列的功能
1. 返回队列首个元素
2. 移除队列首个元素
3. 从后方添加一个元素
4. 返回队列列表
5. 返回队列个数
首先完成第一个功能
返回首个元素,不存在返回undefined
return_one(){
if(this.index>this.top){
return this.queue[this.top]
}
return undefined
}
移除队列首个元素 不存在返回undefined
shift(){
if(this.index>this.top){
let up =this.queue[this.top]
delete this.queue[this.top]
this.top++
return up
}
return undefined
},
从后方添加一个元素
add(value){
this.queue[this.index] = value
this.index++
return value
}
返回队列列表
toString(){
let x = []
for(let i in this.queue ){
x.push(this.queue[i])
}
return x
}
返回队列元素个数
toNumber(){
return this.index-this.top
}
所有代码
class Queue {
constructor(){
this.queue= {},
this.index = 0,
this.top = 0
}
return_one() {
if (this.index > this.top) {
return this.queue[this.top]
}
return undefined
}
shift() {
if (this.index > this.top) {
let up = this.queue[this.top]
delete this.queue[this.top]
this.top++
return up
}
return undefined
}
add(value) {
this.queue[this.index] = value
this.index++
return value
}
toString(){
let x = []
for(let i in this.queue ){
x.push(this.queue[i])
}
return x
}
toNumber(){
return this.index-this.top
}
}
队列还有双端队列,明天写吧,头疼。