数据结构与算法JavaScript这本书算是讲解得比较浅显的,优势就是用javascript语言把经常使用的数据结构给描述了下,书中不少例子来源于常见的一些面试题目,算是与时俱进,业余看了下就顺便记录下来吧javascript
git代码下载:https://github.com/JsAaron/data_structure.gitjava
特殊的列表,栈内的元素只能经过列表的一端访问,栈顶git
后入先出(LIFO,last-in-first-out)的数据结构github
javascript提供可操做的方法, 入栈 push, 出栈 pop,可是pop会移掉栈中的数据面试
实现一个栈的实现类算法
底层存数数据结构采用 数组数组
由于pop是删除栈中数据,因此须要实现一个查找方法 peek数据结构
实现一个清理方法 clear函数
栈内元素总量查找 lengththis
查找是否还存在元素 empty
function Stack(){ this.dataStore = [] this.top = 0; this.push = push this.pop = pop this.peek = peek this.length = length; } function push(element){ this.dataStore[this.top++] = element; } function peek(element){ return this.dataStore[this.top-1]; } function pop(){ return this.dataStore[--this.top]; } function clear(){ this.top = 0 } function length(){ return this.top }
回文就是指一个单词,数组,短语,从前日后从后往前都是同样的 12321.abcba
回文最简单的思路就是, 把元素反转后若是与原始的元素相等,那么就意味着这就是一个回文了
这里能够用到这个栈类来操做
function isPalindrome(word) { var s = new Stack() for (var i = 0; i < word.length; i++) { s.push(word[i]) } var rword = ""; while (s.length() > 0) { rword += s.pop(); } if (word == rword) { return true; } else { return false; } } isPalindrome("aarra") //false isPalindrome("aaraa") //true
看看这个isPalindrome函数,其实就是经过调用Stack类,而后把传递进来的word这个元素给分解后的每个组成单元给压入到栈了,根据栈的原理,后入先出的原则,经过pop的方法在反组装这个元素,最后比较下以前与组装后的,若是相等就是回文了
用递归实现一个阶乘算法
5! = 5 * 4 * 3 * 2 * 1 = 120
用递归
function factorial(n) { if (n === 0) { return 1; } else { return n * factorial(n - 1); } }
用栈操做
function fact(n) { var s = new Stack() while (n > 1) { //[5,4,3,2] s.push(n--); } var product = 1; while (s.length() > 0) { product *= s.pop(); } return product; } fact(5) //120
经过while把n = 5 递减压入栈,而后再经过一个循环仍是根据栈的后入先出的原则,经过pop方法把最前面的取出来与product叠加