实现思路
栈的核心思想为后进先出(LIFO)
实现一个栈需要具备以下功能
- 压栈:添加一个元素到栈顶
- 出栈:移除栈顶的元素并返回
- 获取栈顶元素并返回
- 判断栈是否为空
- 输出栈内的数据
- 清空栈
- 获取栈的大小
实现代码
function Stack() {
this.items = []
Stack.prototype.push = function(elem) {
this.items.push(elem)
}
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.toString = function() {
return this.items.toString()
}
Stack.prototype.clear = function() {
this.items = []
}
Stack.prototype.size = function() {
return this.items.length
}
}
十进制转二进制
function dec2bin(decNumber) {
let stack = new Stack()
while(decNumber > 0) {
stack.push(decNumber % 2)
decNumber = Math.floor(decNumber / 2)
}
let binString = ''
while(!stack.isEmpty()) {
binString += stack.pop()
}
return binString
}