Stack类的实现
function Stack(){
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
function push(element){
this.dataStore[this.top++] = element;
}
function peek(){
return this.dataStore[this.top-1];
}
function pop(){
return this.dataStore[--this.top];
}
function clear(){
this.top = 0;
}
function length(){
return this.top;
}
实例:数制间的相互转换
假设想将数字n转换为以b为基数的数字,实现转换的算法如下:
(1)最高位为n%b,将此位压入栈。
(2)使用n/b代替n
(3)重复步骤1和2,直到n等于0,且没有余数
(4)持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后数字的字符串形式
function mulBase(num,base){
var s = new Stack();
do{
s.push(num % base);
num = Math.floor(num /= base)
}while(num > 0);
var converted = "";
while(s.length() > 0){
converted += s.pop();
}
}
实例:判断一个单词是否是回文
function isPlaindrome(word){
var s = new Stack();
for(var i=0;i<word.length;++i){
s.push(word[i]);
}
var rword = "";
while(s.length() > 0){
rword += s.pop();
}
if(word == rword){
return true;
}else{
return falsej;
}
}
整理自《数据结构与算法Javascript》