function Stack() {
this.dataStore = [];
this.top = 0;//栈顶元素的位置
this.push = push;
this.pop = pop;
this.peek = peek;
this.length=length;
this.clear=clear;
}
function push(element) {//进栈
this.dataStore[this.top++] = element;
}
function pop() {//出栈
return this.dataStore[--this.top];
}
function peek() {//栈顶元素
return this.dataStore[this.top-1];
}
function length() {
return this.top;
}
function clear() {
this.top = 0;
}
//测试栈的实现
var s= new Stack();
s.push("D");
s.push("R");
s.push("B");
console.log(s.length());
console.log(s.peek());
console.log(s.clear());
console.log(s.length());
栈的应用:
(1)数制之间转换
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();
}
return converted;
}
console.log(mulBase(125,8));//输出175
(2)判断回文字符串
function isPalindrome(word) {
var s = new Stack();
for (var i = 0; i < word.length; i++) {
s.push(word[i]);
}
var newStr = "";
while (s.length() > 0) {
newStr += s.pop();
}
if(word === newStr){
return true;
}
return false;
}
(3)使用栈实现递归