JS栈的实现 发表于 2017-06-02 | 栈是一个很基础的数据结构, 属于先进后出类型, 在底层的软件当中有着广泛的应用 下面是相关API代码以及示例代码: 123456789function Stack(){ this.dataStore = []; //用数组实现 this.top = 0; this.push = push; //栈的压入 this.pop = pop; //栈的弹出 this.peek = peek; //栈的顶部元素 this.length = length; this.clear = clear; } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101function push(element) { this.dataStore[this.top++] = element;}function pop(){ return this.dataStore[--this.top];}function peek(){ return this.dataStore[this.top-1];}function length(){ return this.top;}function clear(){ this.top = 0;}//以下为测试代码function test_stack(){ var s = new Stack(); s.push("David"); s.push("Raymond"); s.push("Bryan"); console.log("length: " + s.length()); console.log(s.peek()); var popped = s.pop(); console.log("The popped element is: " + popped); console.log(s.peek()); s.push("Cynthia"); console.log(s.peek()); s.clear(); console.log("length: " + s.length()); console.log(s.peek()); s.push("Cynthia"); console.log(s.peek());}//十进制转换到2至9进制(使用了栈这种结构)function mulBase(num, base) { var s = new Stack(); do { s.push(num % base); num = Math.floor(num /= base); } while (num > 0); var converted = ""; while (s.length() > 0) { converted += s.pop(); } return converted;}//进制转换测试用例function mulBase_test(){ var base = 2; var num = 32; var newNum = mulBase(num, base); console.log(num + "converted to base " + base + " is " + newNum);}//判定给定字符串是否是回文数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; }}//递归计算阶乘function factorial(n) { if (n === 0) { return 1; } else { return n * factorial(n-1); }}//用栈模拟递归过程function fact(n){ var s = new Stack(); while(n > 1) { s.push(n--); } var product = 1; while (s.length() > 0){ product *= s.pop(); } return product;}