使用 JavaScript 实现栈

时间:2021-03-16 20:44:45

1.栈的基本操作

    function Stack() {
//使用数组保存栈元素
var items = []; //添加新元素到栈顶(相当于数组的末尾)
this.push = function(element) {
items.push(element);
}; //移除栈顶的元素,同时返回被移除的元素
this.pop = function() {
return items.pop();
}; //返回栈顶的元素,不对栈做任何修改
this.peek = function() {
return items[items.length - 1];
}; //如果栈里没有任何元素就返回true,否则返回false
this.isEmpty = function() {
return items.length == 0;
}; //移除栈里的所有元素
this.clear = function() {
items = [];
}; //返回栈里的元素个数,和数组的length很像
this.size = function() {
return items.length;
}; //返回栈里的内容
this.print = function() {
//return items.toString();
return items;
};
}

使用该方法:

    var stack = new Stack();
console.log(stack.isEmpty()); //true stack.push(1);
stack.push(3);
stack.push(5);
stack.push(7);
console.log(stack.peek()); //
console.log(stack.print()); //[1, 3, 5, 7]
console.log(stack.isEmpty()); //false
console.log(stack.size()); // console.log(stack.pop()); //
console.log(stack.peek()); //
console.log(stack.print()); // [1, 3, 5]

2.基于该方法实现十进制数转换为二进制数

    //十进制转换为二进制
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;
} var decNumber = 10;
console.log(decNumber + '转换为二进制数为:' + divideBy2(decNumber)); //10转换为二进制数为:1010

3.基于该方法实现十进制数转换为二/八/十六进制数

    //十进制转换为任意进制
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;
} var decNumber = 552;
var base = 16;
console.log(decNumber + '转换为' + base + '进制数为:' + baseConverter(decNumber, base)); //552转换为16进制数为:228