51 lines
862 B
JavaScript
51 lines
862 B
JavaScript
class Stack {
|
|
constructor(items = []) {
|
|
this.items = items; // 用 items 来存储栈的元素
|
|
}
|
|
|
|
// 入栈
|
|
push(item) {
|
|
this.items.push(item);
|
|
}
|
|
|
|
// 出栈
|
|
pop() {
|
|
if (this.isEmpty()) {
|
|
console.log('栈为空! ');
|
|
return undefined; // 栈为空时返回 undefined
|
|
}
|
|
return this.items.pop();
|
|
}
|
|
|
|
// 获取栈顶元素
|
|
peek() {
|
|
if (this.isEmpty()) {
|
|
console.log('栈为空! ');
|
|
return undefined; // 栈为空时返回 undefined
|
|
}
|
|
return this.items[this.items.length - 1];
|
|
}
|
|
|
|
// 判断栈是否为空
|
|
isEmpty() {
|
|
return this.items.length === 0;
|
|
}
|
|
|
|
// 获取栈的大小
|
|
size() {
|
|
return this.items.length;
|
|
}
|
|
|
|
// 清空栈
|
|
clear() {
|
|
this.items = [];
|
|
}
|
|
|
|
// 打印栈内容
|
|
print() {
|
|
console.log(this.items.toString());
|
|
}
|
|
}
|
|
|
|
export default Stack;
|