class Stack{//栈——LIFO后进先出
constructor(){
this.count = 0;
this.items = {};
}
push=(element)=>{
//添加新元素到栈顶
this.items[this.count] = element;
this.count++;
}
pop=()=>{
//移除最后一个元素
if(this.isEmpty()){
return undefined
}
this.count--;
const result = this.items[this.count];
// delete 操作符用于删除对象的某个属性;如果没有指向这个属性的引用,那它最终会被释放。
delete this.items[this.count];
return result;
}
peek=()=>{
//查看栈顶元素
if (this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}
isEmpty=()=>{
//检查栈是否为空
return this.count ===0;
}
size=()=>{
return this.count;
}
clear=()=>{
this.items = {};
this.count = 0;
//或者
/**
* while (!this.isEmpty()) {
this.pop();
}
*/
}
show=()=>{
return JSON.stringify(this)
}
}
//使用
const stack = new Stack();
stack.push(5)
stack.push(8)
console.log(stack.size())
console.log(stack.pop())
console.log(stack.show())
console