js 实现栈
使用数组实现栈
在JavaScript中,可以通过数组来模拟栈的行为。数组的push和pop方法天然适合栈的后进先出(LIFO)特性。

class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return "Underflow";
}
return this.items.pop();
}
peek() {
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());
}
}
使用对象实现栈
对于需要更高性能的场景,可以使用对象来存储栈元素,避免数组的索引调整开销。

class Stack {
constructor() {
this.items = {};
this.count = 0;
}
push(element) {
this.items[this.count] = element;
this.count++;
}
pop() {
if (this.isEmpty()) {
return "Underflow";
}
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
peek() {
return this.items[this.count - 1];
}
isEmpty() {
return this.count === 0;
}
size() {
return this.count;
}
clear() {
this.items = {};
this.count = 0;
}
print() {
console.log(Object.values(this.items).toString());
}
}
栈的应用示例
栈的典型应用包括括号匹配、表达式求值、函数调用栈等。以下是一个括号匹配的示例:
function isBalanced(expression) {
const stack = new Stack();
const map = {
'(': ')',
'[': ']',
'{': '}'
};
for (let char of expression) {
if (char in map) {
stack.push(char);
} else {
if (stack.isEmpty()) return false;
const last = stack.pop();
if (map[last] !== char) return false;
}
}
return stack.isEmpty();
}
console.log(isBalanced("{[()]}")); // true
console.log(isBalanced("{[(]}")); // false
性能考虑
数组实现的栈在大多数情况下性能足够,但对象实现的栈在频繁操作时可能更高效。选择实现方式时应根据具体场景决定。






