一、栈
栈是线性结构,先进后出
新添加或删除的元素保存在栈的同一端,称为栈顶,另一端称为栈底
栈被用在编程语言的编译器和内存保存变量等,在浏览器的历史记录里用到的也是栈
二、基于数组实现
用数组模拟栈,实现以下五个方法:
push: 向栈中压入一个元素
pop: 从栈中弹出一个元素
peek: 获取栈顶元素的值
isEmpty: 判断栈是否为空
size: 获取栈的长度
function Stack() {
this.items = [];
}
Stack.prototype.push = function (element) {
this.items.push(element);
};
Stack.prototype.pop = function () {
return this.items.pop();
};
Stack.prototype.peek = function () {
return this.items[this.items.length - 1];
};
Stack.prototype.isEmpty = function () {
return this.items.length === 0;
};
Stack.prototype.size = function () {
return this.items.length;
};
三、基于对象实现
设计一个栈,最简单的方式是通过数组,但是数组大部分的是时间复杂度是O(n),如果能直接获取元素,并且占用较少的内存空间,我们也可以使用对象来存储栈元素,下面就是用对象模拟一个栈
function Stack() {
this.count = 0;
this.items = {};
}
Stack.prototype.push = function (element) {
this.items[this.count] = element;
this.count++;
};
Stack.prototype.pop = function () {
if (this.isEmpty()) {
return undefined;
}
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
};
Stack.prototype.peek = function () {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
};
Stack.prototype.isEmpty = function () {
return this.count === 0;
};
Stack.prototype.size = function () {
return this.count;
};
四、栈的应用-括号匹配
输入一个字符串,包括大括号、中括号、小括号,写一个函数判断字符串中括号是否匹配。解决这个问题的思路就是:遍历字符串,遇到左括号入栈,遇到右括号,弹出栈顶元素,判断是否与右括号匹配,如果不匹配,返回false
,字符串遍历完,判断栈是否为空,如果不为空,仍然返回false
,最后返回true
,下面是代码实现
let str = "{12*25-(4*3)}";
function isValid(str) {
let stack = [];
for (let item of str) {
if (item === "{" || item === "[" || item === "(") {
stack.push(item);
} else if (item === "}") {
if (stack[stack.length - 1] === "{") {
stack.pop();
} else {
return false;
}
} else if (item === "]") {
if (stack[stack.length - 1] === "[") {
stack.pop();
} else {
return false;
}
} else if (item === ")") {
if (stack[stack.length - 1] === "(") {
stack.pop();
} else {
return false;
}
}
}
if (stack.length) {
return false;
}
return true;
}
console.log(isValid(str));