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;