要求:并要求实现类的in、out、top、size函数,同时要求,执行下面代码时输出预期结果
class Stack{
constructor(){
}
in(value){ // 你的代码 }
out(){ // 你的代码 }
top(){ // 你的代码 }
size(){ // 你的代码 }
}
const stack = new Stack();
stack.in(1);
stack.in(2);
stack.in(3);
stack.top(); //输出3
stack.size(); //输出3
stack.out(); //输出3
stack.top(); //输出2
stack.size(); //输出2
最终代码实现如下:
class Stack{
constructor(){
this.items = []
}
in(value){
this.items.push(value)
}
out(){
if(this.size()<=0) return null
return this.items.pop()
}
top(){
if(this.size()<=0) return null
return this.items[this.size()-1]
}
size(){
return this.items.length
}
}
看下效果: