一、数组构造栈
栈的方法
- push(element):添加一个新元素到栈顶位置
- pop():移除栈顶的元素,同时返回被移除的元素
- peek():返回栈顶的元素,不对栈做任何修改
- isEmpty():如果栈里没有任何元素就返回true,否则返回false
- size():返回栈里的元素个数,这个方法和数组的length属性很类似
- toString:将栈结构的内容以字符串形式返回
function Stack() {
this.items = []
Stack.prototype.push = function(element) {
return this.items.push(element)
}
Stack.prototype.pop = function() {
return this.items.pop()
}
Stack.prototype.peek = function() {
return this.items[this.items.length-1]
}
Stack.prototype.isEmpty = function() {
return this.items.length === 0
}
Stack.prototype.size = function() {
return this.items.length
}
Stack.prototype.toString = function() {
let resultString = ''
for (let i=0; i<this.items.length; i++) {
resultString += this.items[i]
}
return resultString
}
}
二、栈:实现十进制转二进制
思路:取余压栈,出栈拼二进制数
function decimalToBinary(decimalValue) {
var stack = new Stack()
while (decimalValue > 0) {
stack.push(decimalValue % 2) // 取余并压栈
decimalValue = Math.floor(decimalValue / 2) // 取商(向下取整,除去小数)
}
var binaryString = '';
while (!stack.isEmpty()) {
binaryString += stack.pop()
}
return binaryString
}
console.log(decimalToBinary(100)) // 十进制100的二进制为:1100100