概念
栈是一种遵从 后进先出 原则的有序集合。
添加新元素的一端称为栈顶,另一端为栈底。
操作栈的元素时,只能从栈顶操作(添加、移除、取值)
栈的实现
我们需要实现以下功能:
- push() 入栈的方法
- pop() 出栈的方法
- top() 获取栈顶元素的方法
- size() 获取栈中元素个数的方法
- clear() 清空栈的方法
基于 JavaScript 内置对象的方法实现一个数据结构,会对性能有所损耗,所以实现时优先选择传统 JavaScript 对象进行功能的实现。
class Stack {
constructor() {
// 存储栈中数据
this.data = [];
// 记录栈中数据个数(相当于数组的 length )
this.count = 0;
}
// push() 入栈方法
push(item) {
// 方法1:数组方法 push 添加
// this.data.push(item);
// 方法2:利用数组长度
// this.data[this.data.length] = item;
// 方法3:计数方式
this.data[this.count] = item;
this.count++; // 入栈后,count 自增
}
// pop() 出栈方法
pop() {
// 出栈前提是栈中存在元素
if (this.isEmpty()) {
console.log('栈为空!移除失败');
return;
}
// 移除栈顶数据
// 方法1:数组方法 pop移除
// return this.data.pop();
// 方法2:计数方式
const temp = this.data[this.count - 1];
delete this.data[this.count - 1];
this.count--;
return temp;
}
// isEmpty() 检测栈是否为空
isEmpty() {
return this.count === 0;
}
// top() 获取栈顶的元素
top() {
if (this.isEmpty()) {
console.log('栈为空!获取失败');
return;
}
return this.data[this.count - 1];
}
// size() 获取栈中元素个数
size() {
return this.count;
}
// clear() 清空栈
clear() {
this.data = [];
this.count = 0;
}
}
力扣精选题
剑指 Offer 30.包含min函数的栈
LeetCode 剑指 Offer 30. 包含min函数的栈(简单)
方法一:
在存储数据的栈外,再创建一个辅助栈,用于存储栈的最小值 stack = [-2, 0, -3] minStack = [-2, -2, -3]
class MinStack {
constructor() {
// stackA 用于存储数据
this.stackA = [];
this.countA = 0;
// stackB 为辅助栈 用于存储栈道最小值(数据降序排序)
this.stackB = [];
this.countB = 0;
}
push(item) {
// stackA 正常入栈
this.stackA[this.countA] = item;
this.countA++;
// stackB 如果没有数据,直接入栈
// 如果当前元素小于等于 stackB栈顶元素,入栈
if (this.countB === 0 || item <= this.min()) {
this.stackB[this.countB] = item;
} else {
// 否则 入栈元素为 当前栈中最小值
this.stackB[this.countB] = this.min();
}
this.countB++;
}
// 最小值函数 返回栈中最小值 即时辅助栈栈顶元素
min() {
return this.stackB[this.countB - 1];
}
// 获取栈顶元素
top() {
return this.stackA[this.countA - 1];
}
// 出栈
pop() {
delete this.stackA[this.countA - 1];
this.countA--;
delete this.stackB[this.countB - 1];
this.countB--;
}
}
// 时间复杂度:O(1),push(), pop(), top(), min() 四个函数的时间复杂度均为常数级别。
// 空间复杂度:O(N),当共有 N 个待入栈元素时,辅助栈B 需要存储 N 个元素,使用O(N)额外空间。
方法二:
stack = [-2, 0, -3, 2 , -6] minStack = [-2, -3, -6] push():stack 正常入栈,minStack遇到小于等于 min() 元素时入栈 pop():先 检测辅助栈 top() === min() stack ,minStack出栈 再 stackA 正常出栈。
方法三:API大法
class MinStack {
constructor() {
this.stack = [];
}
push(item) {
this.stack.push(item);
}
top() {
return this.stack[this.stack.length - 1];
}
min() {
// return Math.min(...this.stack);
return Math.min.apply(null, this.stack);
}
pop() {
this.stack.pop();
}
}