栈的实际应用非常的广泛。在回溯问题中,它可以存储访问过的任务或者路径,撤销的操作等等。
从十进制到二进制
要把十进制转化成二进制,我们可以将该十进制数字和2整出,直到结果是0为止。
function Stack(){
let items = [];
// 向栈添加元素
this.push = function(ele){
items.push(ele);
}
// 从栈移出元素
this.pop = function(){
return items.pop();
}
// 查看栈顶元素
this.peek = function(){
return items[items.length-1];
}
// 检查栈是否为空
this.isEmpty = function(){
return items.length == 0;
}
// 清空栈
this.clear = function(){
items = [];
}
// 打印栈元素
this.print = function(){
console.log(items.toString());
}
}
function divideByTwo(num){
var remStack = new Stack(),
rem,
bString = '';
while(num > 0){
rem = Math.floor(num % 2);
remStack.push(rem);
num = Math.floor(num / 2);
}
while(!remStack.isEmpty()){
bString += remStack.pop().toString();
}
console.log(bString);
return bString;
}
测试:
divideByTwo(4); //100
divideByTwo(10) //1010
修改算法,把十进制转换成任意进制
function Stack(){
let items = [];
// 向栈添加元素
this.push = function(ele){
items.push(ele);
}
// 从栈移出元素
this.pop = function(){
return items.pop();
}
// 查看栈顶元素
this.peek = function(){
return items[items.length-1];
}
// 检查栈是否为空
this.isEmpty = function(){
return items.length == 0;
}
// 清空栈
this.clear = function(){
items = [];
}
// 打印栈元素
this.print = function(){
console.log(items.toString());
}
}
function divideByAny(num, base){
var remStack = new Stack(),
rem,
bString = '',
converts = '0123456789ABCDEF';
while(num > 0){
rem = Math.floor(num % base);
remStack.push(rem);
num = Math.floor(num / base);
}
while(!remStack.isEmpty()){
bString += converts[remStack.pop()];
}
console.log(bString);
return bString;
}
测试:
divideByAny(8, 2); //1000
divideByAny(8, 8); //10
divideByAny(16, 8); //20
divideByAny(16, 16); //10