js底层复现之队列

昨天复现了栈,栈是先进后出,而队列遵从先进先出原则,就类似我们排队打饭,第一个到的一定是第一打饭走的,也像极了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
		}

}

队列还有双端队列,明天写吧,头疼。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自信小老头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值