要求:并要求实现类的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
}
}
看下效果:

栈实现
本文介绍了一个简单的栈类实现,包括in(入栈)、out(出栈)、top(查看栈顶元素)和size(获取栈大小)等核心函数。通过具体示例展示了如何使用该栈类进行基本操作。
839

被折叠的 条评论
为什么被折叠?



