方法
- 入栈
- 出栈
- 查看栈首
- 查看长度
实现
function Stack() {
this.list = [];
// 入栈 push
Stack.prototype.push = function (item) {
this.list.push(item);
};
// 出栈 pop
Stack.prototype.pop = function () {
return this.list.pop();
};
// 查看下一个出栈的 peek
Stack.prototype.peek = function () {
return this.list[this.list.length - 1];
};
Stack.prototype.size = function () {
return this.list.length;
};
}
功能测试
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.size(); // 3
console.log(stack.peek()); // 3
stack.pop(); // 3
console.log(stack.peek()); // 2
stack.pop(); // 2
stack.pop(); // 1
十进制转二进制
思路
对某数对2取余,余数入栈,整数结果再进行取余,入栈……,直到整数结果等于0
实现
// 基于栈
function dec2bin(dec) {
const binStack = new Stack();
while (dec > 0) {
binStack.push(dec % 2);
dec = Math.floor(dec / 2);
}
let result = "";
while (binStack.size() > 0) {
result += binStack.pop();
}
return result;
}
测试
dec2bin(10); // 1010
dec2bin(32); // 10000
dec2bin(87); // 1010111
dec2bin(100); // 1100100
dec2bin(123); // 1111011
dec2bin(325); // 101000101
dec2bin(687); // 1010101111
参考
- 小马哥 – JS数据结构与算法