js基础算法之 栈

首先说到栈,相信对很多学编程的朋友们都不陌生,他遵从后进先出原则,什么意思呢? 删除从后方往前方删除,就像平时大家摞起来的物品一样,想要拿掉物品,需要从最上方开始一个一个拿走,他也被诸多编程语言用来在内存中保存变量,方法等等。
话不多说,用js复现一个栈出来。
因为栈不能从中间抽离,所以我们的方法包括一下几条:
1. 查看栈顶
2. 删除栈顶
3. 添加元素
4. 清空栈
5. 返回栈中元素个数

于是我就写了inn类,并且赋予一个show 的数组作为栈展示出来

class inn{
			constructor(){
				this.show=[]
			}
		}

下面添加查看栈顶方法

looktop(){
				if(this.show[this.show.length-1]==undefined){
					return null
				}else{
					return this.show[this.show.length-1]
				}
			}

下面添加删除栈顶方法,因为数组自带pop方法,不需要我们自己手写,直接拿来调用

pop(){
				return this.show.pop()
}

下面添加添加元素的方法

add(...arr){
				for(let c of arr){
					arr[arr.length] = c
				}
			}

清空

over(){
				this.show = []
	}

返回栈中个数

number(){
				return this.show.length
}

ok,整体就搞定了

class inn{
	constructor(){
		this.show=[]
	}
	looktop(){
		if(this.show[this.show.length-1]==undefined){
			return null
		}else{
			return this.show[this.show.length-1]
		}
	}
	pop(){
		return this.show.pop()
	}
	add(...arr){
		for(let c of arr){
			this.show[this.show.length] = c
			console.log(c)
		}
	}
	over(){
		let o = this.show
		this.show = []
		return o
	}
	number(){
		return this.show.length
	}
}

顺带一提, 今天哥们的证已经下来了,等了好几天,终于还是过了。
在这里插入图片描述还有,我永远相信我的国家。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

自信小老头

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

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

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

打赏作者

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

抵扣说明:

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

余额充值