栈
1,特点
后进先出(javaScript没有栈,用Array实现),删除和添加都在同一端操作;LIFO(last in first out)
2,操作
- push:向数组末尾添加新项目,并返回新长度(改变原始数组); 入栈;
- pop:移除数组的最后一个元素,并返回该元素(改变原始数组);出栈;
- stack[stack.length-1]:栈顶元素
3,数据结构
const stack = [];
stack.push("Blue"); // ["Blue"]
stack.push("Yellow"); // ["Blue", "Yellow"]
stack.push("Red"); // ["Blue", "Yellow", "red"]
stack.pop(); // ["Blue", "Yellow"]
stack[stack.length - 1]; // Yellow
4,练习题
20. 有效的括号
// 越靠后的左括号,对应右括号越靠前(后进先出);左括号入栈,右括号出战,栈空就合法;
var isValid = function (s) {
if (s.length % 2 !== 0) return false;
const stack = [];
const map = new Map();
map.set("(", ")");
map.set("[", "]");
map.set("{", "}");
for (let i = 0; i < s.length; i++) {
let str = s[i];
if (map.has(str)) {
stack.push(str); // 左括号入栈
} else {
const temp = stack[stack.length - 1];
// 当前值和栈顶元素是否匹配
if (map.get(temp) === str) {
stack.pop(); //匹配 出栈
} else {
return false; // 不匹配结束
}
}
}
return stack.length === 0; // 栈空合法
};
队列
1,特点
先进先出(javaScript没有栈,用Array实现);从第一名开始处理,新来的排在队尾; FIFO(first in first out)
2,操作
- push:向数组末尾添加新项目,并返回新长度(改变原来数组); 入队;
- shift:移除数组的第一项;并返回该元素(改变原始数组); 出队;
- queue[0]:对首;
3,数据结构
const queue = [];
queue.push(1); // [1]
queue.push(2); // [1,2]
queue.push(3); // [1,2,3]
queue.shift(); // [2,3]
queue[0]; // 2
4,练习题
933. 最近的请求次数
// 新来的入队,不在3000内的出队;
var RecentCounter = function () {
this.queue = [];
};
RecentCounter.prototype.ping = function (t) {
this.queue.push(t); // 入队
while (this.queue[0] < t - 3000) {
this.queue.shift(); // 出队
}
return this.queue.length;
};