栈
栈概念和用途
- 栈是一种特殊的列表。
- 栈是一种高效的数据结构,因为数据只能在栈顶删除或增加,操作很快。
- 栈的使用遍布程序语言实现方方面面,从表达式求值到处理函数调用。
栈关键概念定义
- 栈内元素只能通过列表的一端访问,这一端成为
栈顶(反之栈底) - 栈被称为一种
后入先出(LIFO,last-in-first-out)的数据结构 - 插入新元素又称作
进栈、入栈或压栈,从一个栈删除元素又称作出栈或退栈
经典的操作:"洗盘子"
class Stack {
constructor() {
this.dataStore = {};// 保存栈内元素
this.top = 0; //标记可以插入新元素的位置,栈内压入元素=>该变量变大,弹出元素=>变量减小
}
// 入栈操作 注意 this.top++ 是后加
push(element) {
this.dataStore[this.top++] = element;
}
// 出栈操作
pop() {
if (this.isEmpty()) {
return undefined;
}
const item = this.dataStore[--this.top];
delete this.dataStore[this.top];
return item;
}
// 返回栈顶的元素
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.dataStore[this.top - 1];
}
// 返回栈内元素的个数
length() {
return this.top;
}
isEmpty() {
return this.length() === 0
}
// 清空一个栈
clear() {
// this.top = 0;
// this.dataStore = [];
while (!this.isEmpty()){
this.pop();
}
}
}
回文数:
const isPalindrome = (word) => {
const stack = new Stack();
for (let i = 0; i < word.length; i++) {
stack.push(word[i]);
}
let str = "";
while (stack.length() > 0) {
str += stack.pop()
}
return str === word;
};
const str = "racecar";
console.log(isPalindrome(str)); // true