1. 实现源码
var Stack = function(){
function pop(){
return this.dataStore[--this.top];
};
function push(element){
this.dataStore[this.top++] = element;
};
function peek(){
return this.dataStore[this.top-1];
};
function clear(){
this.top = 0;
this.dataStore = [];
};
function length(){
return this.top;
};
this.dataStore = [];
this.top = 0;
this.pop = pop;
this.push = push;
this.peek = peek; //只获取栈顶元素,不删除
this.length = length;
this.clear = clear;
}
2.应用实例
- 利用栈结构进行数字的进制转换
function mulBase(num, base){
var st = new Stack();
st.push(num%base);
while(Math.floor(num/base) > 0) {
num = Math.floor(num/base);
st.push(num%base);
}
var converted = '';
while(st.length()){
converted += st.pop();
}
return converted;
}
mulBase(32, 2); // "100000"
mulBase(125, 8); // "175"
- 判断回文字符串
function isPalindrome(word){
var st = new Stack();
for(var i = 0; i < word.length; i++) {
st.push(word[i]);
}
var reversedWord = '';
while(st.length() > 0) {
reversedWord += st.pop();
}
return word === reversedWord;
}
isPalindrome('aba'); // true
isPalindrome('abc'); // false
其实判断字符串是否是回文字符只需用字符串的reverse
方法即可。
- 检测算数表达式中的括号是否匹配
function testPamphlet(expr){
var st = new Stack();
var flag = (function(){
for(var i = 0; i < expr.length; i++) {
switch (expr[i]){
case '(':
st.push('(');
break;
case ")":
if(st.peek() === "("){
st.pop();
break;
}else{
return false;
}
default:
break;
}
}
if(st.length() > 0) {
return false;
}
return true;
})();
return flag;
}
testPamphlet('2.3 + 23 / 12 + (3.14159×0.24)'); // true
testPamphlet('2.3 + 23 / 12 + (3.14159×0.24'); // false