在JavaScript中,可以使用数组来实现栈的功能。栈是一种后进先出(LIFO)的数据结构。
下面是实现代码:
class Stack {
constructor() {
this.items = [];
}
// 入栈操作
push(element) {
this.items.push(element);
}
// 出栈操作
pop() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items.pop();
}
// 查看栈顶元素
peek() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items[this.items.length - 1];
}
// 检查栈是否为空
isEmpty() {
return this.items.length == 0;
}
// 清空栈
clear() {
this.items = [];
}
// 返回栈的大小
size() {
return this.items.length;
}
}