首先说到栈,相信对很多学编程的朋友们都不陌生,他遵从后进先出原则,什么意思呢? 删除从后方往前方删除,就像平时大家摞起来的物品一样,想要拿掉物品,需要从最上方开始一个一个拿走,他也被诸多编程语言用来在内存中保存变量,方法等等。
话不多说,用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
}
}
顺带一提, 今天哥们的证已经下来了,等了好几天,终于还是过了。
还有,我永远相信我的国家。