堆栈,我们总是把新的数据加在堆栈的最顶端,移除的时候也是从最顶端开始移除。也叫LIFO(last in first out)。
代码实现(javascript)
class Stack {constructor(... items) {this.items = items; } clear() {this.items.length = 0;}clone() {return new Stack(...this.items); } contains(item) {return this.items.includes(item);} peek() {let itemsLength = this.items.length;let item = this.items[itemsLength - 1];return item; } pop() {let removedItem = this.items.pop();return removedItem; } push(item) {this.items.push(item);return item; } }
使用Stack()
let myStack = new Stack();// Add items myStack.push("One"); myStack.push("Two"); myStack.push("Three");// Preview the last item myStack.peek(); // Three// Remove item let lastItem = myStack.pop(); console.log(lastItem); // Three myStack.peek(); // Two// Create a copy of the stack let newStack = myStack.clone();// Check if item is in Stack newStack.contains("Three"); // false
时间复杂度
动作 | 最佳 | 平均 | 最差 |
Push | O(1) | O(1) | O(1) |
Pop | O(1) | O(1) | O(1) |
Peek | O(1) | O(1) | O(1) |
Search/Contains | O(1) | O(n) | O(n) |
Memory | O(n) | O(n) | O(n) |