数据结构与算法JavaScript描述-个人练习(Stack)

#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;
};

转载于:https://my.oschina.net/xixine/blog/471539

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值