栈是一种后进先出(LIFO)的有序集合,新添加的元素保存在栈顶,旧元素靠近栈底。
下面列出实现栈的代码(JavaScript语言描述):
//本代码实现栈/**
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];
}
/**
* 确定栈是否为空
* @return {Boolean} 若栈为空则返回true,不为空则返回false
*/
this.isEmpty = function() {
return items.length === 0
};
/**
* 清空栈中所有内容
*/
this.clear = function() {
items = [];
};
/**
* 返回栈的长度
* @return {Number} 栈的长度
*/
this.size = function() {
return items.length;
};
/**
* 以字符串显示栈中所有内容
*/
this.print = function() {
console.log(items.toString());
};
}
栈的使用案例:
1、从十进制到二进制:
function divideBy2(num) {
var remStack=new Stack(),
rem, //同于var rem;
binaryString="";
while(num>0){
rem=Math.floor(num%2);//Math.floor(x) 函数返回小于或等于数 "x" 的最大整数。
remStack.push(rem);
num=Math.floor(num/2);
}
while(!remStack.isEmpty()){
binaryString+=remStack.pop().toString();//toString()方法属于Object对象,由于所有的对象都"继承"了Object的对象实例,因此几乎所有的实例对象都可以使用该方法。
}
return binaryString;
}
2.传入任意进制的基数为参数,编写由十进制转为任意进制的算法:
function baseConverter(num,base) {//base最大为16
var remStack=new Stack(),
rem,
stringBase="",
digits="0123456789ABCDEF";
while(num>0){
rem=Math.floor(num%base);
remStack.push(rem);
num=Math.floor(num/base);
}
while(!remStack.isEmpty()){
stringBase+=digits[remStack.pop()].toString();
}
return stringBase;
}