《学习javascript数据结构与算法》——第三章:栈
栈是一种遵从后进先出(LIFO)原则的有序集合
创建栈,并为栈声明方法
function Stack() {
var items = [];
//push()添加一个或多个元素到栈顶
this.push = function(element) {
items.push(element);
};
//pop()移除栈顶的元素,并返回被移除的元素
this.pop = function() {
return items.pop();
};
//peek()返回栈顶的元素,不对栈做任何修改
this.peek = function() {
return items[items.length-1];
};
//isEmpty(),如果栈里没有元素就返回true,否则返回false
this.isEmpty = function() {
return items.length === 0;
};
//size()返回栈里的元素的个数
this.size = function() {
return items.length;
};
//clear()移除栈里所有的元素
this.clear = function() {
items = [];
};
//print()把栈里的元素都输出到控制台
this.print = function() {
console.log(items.toString());
};
this.toString = function() {
return items.toString();
};
}
从十进制到二进制
将十进制数和2整除,直到结果为0
function divideBy2(decNumber) {
var remStack = new Stack(),
rem,
binaryString = '';
while (decNumber > 0) {
rem = Math.floor(decNumber % 2);
remStack.push(rem);
decNumber = Math.floor(decNumber / 2);
}
while (!remStack.isEmpty()) {
binaryString += remStack.pop().toString();
}
return binaryString;
}
pop()将栈里面的元素都移除到binaryString,然后toString()将其连接成字符串
一般化为将十进制转化为任意进制
function baseConverter(decNumber, base) {
var remStack = new Stack(),
rem,
baseString = '',
digits = '0123456789ABCDEF';
while (decNumber > 0) {
rem = Math.floor(decNumber % base);
remStack.push(rem);
decNumber = Math.floor(decNumber / base);
}
while (!remStack.isEmpty()) {
baseString += digits[remStack.pop()];
}
return baseString;
}