#Data Structure - Stack @(Data Structure & Algorithm) ##Define
//define stack
var Stack = function(){
this.dataStore = [];
this.top = 0;
}
Stack.prototype = {
constructor: Stack,
push: function(el){
this.dataStore[this.top++] = el;
},
pop: function(){
return this.dataStore[--this.top];
},
peek: function(){
return this.dataStore[this.top - 1];
},
clear: function(){
this.dataStore = [];
this.top = 0;
},
getSize: function(){
return this.top;
}
};
##Number system conversion
//for base from 2~9
var nsc = function(num, base){
var result = "",
s = new Stack(),
res = num;
do{
s.push(res % base); //余数入栈
res = Math.floor(res / base); //商继续loop
} while (res > 0);
while (s.getSize() > 0){
result += s.pop();//恰好需要倒序
}
return result;
}
##is Palindrom
function isPalindrom(str){
var s = new Stack(),
i;
//恰好需要逆序,入栈
for (i = 0; i < str.length; i++){
s.push(str[i]);
}
i = 0;
//逐位出栈与正序原字符串比较,遇到不同则退出loop
while (s.pop() === str[i] && i < str.length){
i++;
}
//若已loop完整个字符串则为回文
if (i === str.length) return true;
else return false;
};