栈
- 栈是一种线性数据结构,用于存储一组有序的元素。
- 栈的元素遵循 LIFO(后进先出)的原则,即最后进入的元素最先出栈。
- 栈有两个基本操作:push(入栈)和 pop(出栈)。
- 栈还有一个常用的操作:peek(查看栈顶元素)。
栈的实现
function Stack() {
this.items = [];
// 1.入栈
Stack.prototype.push = function (element) {
return this.items.push(element);
};
// 2.出栈
Stack.prototype.pop = function () {
return this.items.pop();
};
// 3.查看栈顶元素
Stack.prototype.peek = function () {
return this.items[this.items.length - 1];
};
// 4.判断栈是否为空