1.特点
后进先出、受限制的线性结构
2.实现
通过js的数组,能够轻松完成封装其所有基本功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function Stack(){ this.items = [];
Stack.prototype.push = function (element) { this.items.push(element); } Stack.prototype.pop = function () { return this.items.pop(); } Stack.prototype.peek = function () { return this.items.peek(); } Stack.prototype.isEmpty = function () { return this.items.length == 0; } Stack.prototype.size = function () { return this.items.length; } Stack.prototype.toString = function(){ var resultString = ''; for(var i = 0; i < this.items.length; i++){ resultString += this.items[i] + ' '; } return resultString; } }
|
3.实际应用
1.leetcodeT504
问题描述:
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
示例 2:
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var convertToBase7 = function(num) { var a = num; var arr = []; var isFu = false; if(a < 0){ isFu = true; a = a * -1; } if(a == 0){ return '0'; } while(a != 0){ arr.push(a % 7); a = Math.floor(a / 7); } var resultStr = ''; for(var i = arr.length-1; i >= 0 ; i--){ resultStr += arr[i]+''; } if(isFu){ resultStr = '-' + resultStr; } return resultStr; };
|