栈是一种高效的数据结构,由于数据只能在栈顶添加或删除,因此这样的操做很快且很容易实现。算法
栈是一种特殊的列表,栈内的元素只能经过列表的一端访问,这一端称之为栈顶。
栈被称为一种后入先出(LIFO,last-in-first-out)的数据结构。
因为栈具备后入先出的特色,因此任何不在栈顶的元素都没法访问,咱们必须先拿掉上面的元素才能访问其栈底的元素。
对栈的主要操做是将一个元素压入栈和将一个元素弹出栈,入栈使用push()
方法,出栈使用pop()
方法。数组
咱们将使用JavaScript实现栈结构,各部分功能使用注释说明。
存储数据咱们使用的是数组。数据结构
/** * Stack 构造方法 */ function Stack () { this.dataStore = [] this.top = 0 this.push = push this.pop = pop this.peek = peek this.clear = clear this.length = length } /** * push() 该方法用于向栈压入元素 * 向栈中压入一个新元素,将其保存在数组中变量top所对应的位置 * 而后将 top + 1 让其指向数组中下一个空位置 * @param {*} element */ function push (element) { this.dataStore[this.top++] = element } /** * pop() 该方法用于从栈顶推出元素 * 返回栈顶元素,同时将变量top - 1 */ function pop () { return this.dataStore[--this.top] } /** * peek() 该方法用于返回数组的第 top - 1 个位置的元素 */ function peek () { return this.dataStore[this.top - 1] } /** * length() 该方法用于获取栈的长度 * 返回当前top值便可得到栈内元素个数 */ function length () { return this.top } /** * clear() 该方法用于清空栈 * 将top设为0 */ function clear () { this.top = 0 }
咱们能够利用栈将一个数字从一种数制转换为另外一种数制。
假设想将数字n转换为以b为基数的数字,实现的算法以下:this
此算法只针对基数为2-9的状况
代码实现以下:code
function mulBase (num, base) { let s = new Stack() do { s.push(num % base) num = Math.floor(num /= base) } while (num > 0) { let converted = '' while (s.length() > 0) { converted += s.pop() } return converted } }
使用栈,咱们能够判断一个字符串是否为回文。
字符串完整压入栈内后,经过持续弹出栈中的每个字母就能够获得一个新的字符串,该字符串恰好与原来的字符串顺序相反。咱们只须要比较两个字符串便可。若是相等,就是一个回文。ip
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() } if (word == rword) { return true } else { return false } }
以上就是对JavaScript实现栈的介绍。element
参考资料:数据结构与算法JavaScript描述 第4章 栈