概念
定义
栈内元素只能通过一端访问,即栈顶、栈底
栈被称为一种后入先出 LIFO 的数据结构
进栈、入栈、压栈
出栈、退栈
代码实现
function Stack() {this.stackStore = []this.top = 0this.push = pushthis.pop = popthis.peek = peekthis.clear = clearthis.getLength = getLength}function push(ele) {this.stackStore[this.top++] = ele}function pop() {if (this.top === 0) return null// 第一次实现,下面写成了这样子,导致pop为undefined// return this.stackStore[this.top--]// 然后改成了这个样子// return this.stackStore[this.top-- - 1]// 然后看了一下实现,改成这样子更符合人类思维一点= =return this.stackStore[--this.top]}function peek() {return this.stackStore[this.top - 1]}function clear() {this.top = 0this.stackStore = []}function getLength() {return this.top}var s = new Stack(),log = console.log,warn = console.warns.push('n1')s.push('n2')s.push('n3')log(s.peek())log(s.getLength())log(s.pop())log(s.peek())// 回文算法function checkHuiWen(str) {if (!str || typeof str !== 'string') return falselet stack = new Stack(),res = ''for (let i = 0; i < str.length; i++) {stack.push(str[i])}while(stack.top != 0) {res += stack.pop()}console.log(res)if (res === str) {return true}return false}warn(checkHuiWen('啊撒旦风口浪尖阿斯顿发链接'))
作用
回文算法,里面用栈存储并退栈拼接
