您的位置:首页 > 理论基础 > 数据结构算法

栈的实现 -- 数据结构与算法的javascript描述 第四章

2014-09-12 17:33 323 查看

栈 :last-in-first-out


栈有自己特殊的规则,只能 后进入的元素 ,最先被推出来,我们只需要模拟这个规则,实现这个规则就好。 peek是返回栈顶元素(最后一个进入的)。


/**
* 栈 后入先出
* @constructor
*/
function Stack(){
this.pop = pop;
this.push = push
//栈顶位置
this.top= 0;
this.length = 0;
this.dataStore = [];
this.peek = peek;
this.clear = clear;
this.length = length;

//返回栈顶元素
function peek(){
return this.dataStore[this.top-1];
}

function clear(){
this.top=0;
this.dataStore=[];
}
function length (){
return this.top;
}
function pop(){
return this.dataStore[--this.top];
}
function push(element){
this.dataStore[this.top++]=element;
}

function empty(){}

}
//栈的应用
/**
* 进制转换
* @param num  数字 *10进制
* @param base  转换进制 任何进制
* @returns {string}
*/
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;
}
var s = mulBase(32,2)
console.log(s)

/**
* 判断字符是否  回文    *回文是指这样一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的。
* @param word
* @returns {boolean}
*/
function ishuiwen(word){
var s = new Stack()
for(var i=0;i<word.length;i++){
s.push(word[i])
}
var foword = '';

while(s.length()>0){
foword+=s.pop()
}
return word==foword;
}
var hs = 'aca'
console.log(hs+"判断是否回文:"+ishuiwen(hs))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: