栈的定义:后入先出的数据结构。
定义一个栈构造函数,利用数组做缓存。
function Stack(){ this.dataStore = [] this.top = 0 // 压入一个新元素 this.push = function(element){ this.dataStore[this.top++] = element } // 返回一个栈顶元素 同时将变量top减- this.pop = function(){ return this.dataStore[--this.top] } // 返回栈顶元素 this.peek = function(){ return this.dataStore[this.top-1] } // 返回元素个数 this.length = function(){ return this.top } // 清空栈 this.clear = function(){ this.top = 0 } }
使用举例:
1,判断是否是回文
// 判断是否是回文 其实判断回文完全没必要这么复杂的 这里只是演示 function isPalindrome(word){ let s = new Stack() // 创建栈 for(let i =0; i <word.length; i++){ s.push(word[i]) } // 返序 let rword = '' while(s.length() > 0){ rword +=s.pop() } // 是否相等 return word === rword }
2,使用栈模拟阶乘
// 使用栈模拟递归过程 function fact(){ let s= new Stack() // 先放入堆栈里 while(n > 1){ s.push(n--) } // 然后遍历使用 let product = 1 while(s.length() >0){ product*=s.pop() } return product }
栈也是一种建模单元,和队列有很大的相似之处,使用的逻辑同样是构建栈、然后遍历作为主逻辑、其他做幅逻辑。