From 27d3b489e32db12655cb8fed036c904f42f99efd Mon Sep 17 00:00:00 2001 From: LouisFonda Date: Fri, 7 Mar 2025 20:24:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=A0=88=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stack/index.js | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 stack/index.js diff --git a/stack/index.js b/stack/index.js new file mode 100644 index 0000000..110b5d0 --- /dev/null +++ b/stack/index.js @@ -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;