feat: 添加栈数据结构

This commit is contained in:
LouisFonda 2025-03-07 20:24:37 +08:00
parent 89042e81a8
commit 27d3b489e3
Signed by: yigencong
GPG Key ID: 29CE877CED00E966

50
stack/index.js Normal file
View File

@ -0,0 +1,50 @@
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;