JavaScript系列- 数据结构:栈
栈是一种先进后出,后进先出的数据结构,类似于我们往箱子里放东西,先放进去的总是最后才能拿出来,最后放进去的总是最先拿出来。
class stack {
constructor() {
this.items = []; // 此处的基础数据为数组
}
push(node) {
this.items.push(node);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
}
我们利用栈的特性来实现一个十进制转二进制八进制十六进制的函数,如下:
class Stack {
constructor() {
this._i = Symbol("stack");
this[this._i] = {};
this.length = 0;
}
push(node) {
this[this._i][this.length] = node;
this.length++;
}
pop() {
if (this.isEmpty()) {
return null;
}
this.length--;
const r = this[this._i][this.length];
delete this[this._i][this.length];
return r;
}
getItems() {
return this[this._i];
}
// 获取栈顶结点
peek() {
if (this.isEmpty()) {
return null;
}
return this[this._i][this.length - 1];
}
isEmpty() {
return this.length === 0;
}
clear() {
this[this._i] = {};
this.length = 0;
}
}
// 十进制转二进制
function decimalToBinary(number, bs) {
const stack = new Stack();
const charSet = "0123456789ABCDEF";
let result = "";
while (number > 0) {
// 每次计算余数放进栈中
stack.push(number % bs);
// 计算下一次参与运算的结果
number = Math.floor(number / bs);
}
while (!stack.isEmpty()) {
result += charSet[stack.pop()];
}
return result;
}
console.log(decimalToBinary(520520, 16));
LeetCode题目
给定一组字符串,判断此组字符串是否被正确闭合
class Stack {
constructor() {
this._i = Symbol("stack");
this[this._i] = {};
this.length = 0;
}
push(node) {
this[this._i][this.length] = node;
this.length++;
}
pop() {
if (this.isEmpty()) {
return null;
}
this.length--;
const r = this[this._i][this.length];
delete this[this._i][this.length];
return r;
}
getItems() {
return this[this._i];
}
// 获取栈顶结点
peek() {
if (this.isEmpty()) {
return null;
}
return this[this._i][this.length - 1];
}
isEmpty() {
return this.length === 0;
}
clear() {
this[this._i] = {};
this.length = 0;
}
}
// 十进制转二进制
function decimalToBinary(number, bs) {
const stack = new Stack();
const charSet = "0123456789ABCDEF";
let result = "";
while (number > 0) {
// 每次计算余数放进栈中
stack.push(number % bs);
// 计算下一次参与运算的结果
number = Math.floor(number / bs);
}
while (!stack.isEmpty()) {
result += charSet[stack.pop()];
}
return result;
}
function isValid(s) {
const stack = new Stack();
// Array.prototype.forEach.call(s, (item) => stack.push(item));
for (let i = 0; i < s.length; i++) {
const c = s[i];
const p = stack.peek();
if (
(c === ")" && p === "(") ||
(c === "]" && p === "[") ||
(c === "}" && p === "{")
) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
console.log(isValid("({([])})"));
利用栈的思想,我们可以得到一些启发:
如: 用户选择一条数据,每次只能选择一条
撤销回退和前进操作