数据结构----栈

//

/*
* 栈被称为一种后入先出(LIFO,last-in-first-out)的数据结构。
*
* push : 入栈
* pop: 出栈
* top: 栈顶位置 初始化为0 表示栈顶对应数组的起始位置 0  1--》对应数组第一个元素  top-1  就是栈顶元素
peek: 预览栈顶的元素 不从栈中删除
clear: 清除栈中的元素 *
*/ function 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 Stack() { this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.length = length; this.clear = clear; } // var s = new Stack(); // // s.push("David"); // s.push("Raymond"); // s.push("Bryan"); // // console.log(s.length(),s.peek()) //列子 转化进制 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; } console.log(mulBase(32,2)); //判断是否是回文 function isPalindrome(word) { var s = new Stack(); word = word.toString(); for(var i = 0 ; i< word.length;i++) { s.push(word[i]); } var rword = ""; while (s.length() > 0) { rword += s.pop(); } return word === rword; } console.log(isPalindrome(1011)); //模拟递归 function fact(num) { var s = new Stack(); for(var i = num; i >= 1; i--) { s.push(i); } var product = 1; while (s.length() > 0) { product *= s.pop(); } return product; } console.log(fact(5));

 

原文地址:https://www.cnblogs.com/yunnex-xw/p/9818145.html