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》