栈的封装
//栈 先进后出 //利用js数组来进行封装 function Stack () { this.items = [] //入栈 Stack.prototype.push = function (element) { this.items.push(element) } //出栈 Stack.prototype.pop = function () { this.items.pop() } //查看栈顶元素 Stack.prototype.peek = function () { return this.items[0] } //栈内元素的个数 Stack.prototype.size = function () { return this.items.length } Stack.prototype.isEmpty = function () { return this.items.length == 0 } Stack.prototype.toString = function () { var str = '' for(var i = 0; i < this.items.length; i++) { str += this.items[i] + ' ' } return str } }
//十进制转化为二进制问题
function dec2bin(decimal) {
var stack = new Stack()
while(decimal/2 > 0) {
stack.push(decimal%2)
decimal = Math.floor(decimal/2)
}
var str = ''
while(!stack.isEmpty()) {
str += stack.pop()
}
return str
}