-
-
Save qwasfun/670a118ffca4b1807a1b19b41b0e7c20 to your computer and use it in GitHub Desktop.
基于数组实现栈 Stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Stack { | |
| constructor() { | |
| this.stack = []; | |
| } | |
| // 向栈添加元素 | |
| push(item) { | |
| this.stack.push(item); | |
| } | |
| // 从栈中移除元素 | |
| pop() { | |
| return this.stack.pop(); | |
| } | |
| // 查看栈顶元素 | |
| peek() { | |
| return this.stack[this.stack.length - 1]; | |
| } | |
| // 检查栈是否为空 | |
| isEmpty() { | |
| return this.stack.length === 0; | |
| } | |
| // 栈的长度 | |
| size() { | |
| return this.stack.length; | |
| } | |
| // 清空栈元素 | |
| clear() { | |
| this.stack = []; | |
| } | |
| } | |
| let stack = new Stack(); | |
| console.log(stack.isEmpty()); // true | |
| stack.push(5); | |
| console.log(stack.peek()); | |
| stack.push(11); | |
| console.log(stack.size()); // 输出 3 | |
| stack.push(15); | |
| stack.pop(); | |
| stack.push("Hello World"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment