栈的使用(JavaScript)

从十进制转换成二进制

这里写图片描述

function Stack(){//首先,申明一个类
    var item = []; //使用一种数据结构来保存栈内元素
    //声明常用方法
    this.push = function(v){//添加一个(或几个)新元素到栈顶 
        item.push(v);
    }
    this.pop = function(){//移除栈顶的元素,同时返回被移除的元素
        return item.pop();
    }
    this.peek = function(){//返回栈顶的元素,不对栈做任何修改
        return item[item.length-1];
    }
    this.isEmpty = function(){//如果栈里没有任何元素就返回true,否则返回false
        return !item.length;
    }
    this.clear = function(){//移除栈里的所有元素
        item = [];
    }
    this.size = function(){//返回栈里的元素个数
        return item.length;
    }
    this.print = function(){
        console.log(item.toString());
    }
}
function tenBytwo(Number){
    var stack =new Stack(),
        remainder,
        Binary = '';
    while(Number > 0){
        remainder = Math.floor(Number % 2);
        Number = Math.floor(Number / 2);
        stack.push(remainder);
    }
    while(!stack.isEmpty()){
        Binary += stack.pop();
    }
    console.log(Binary);
}
tenBytwo(133);

逆波兰表示法的计算

function rePoland(arr){
    var stack = new Stack();
    for(var i=0; i<arr.length; i++){
        if(typeof(arr[i]) == 'number'){
            stack.push(arr[i]);
        }
        else if(arr[i] == '+'){
            stack.push(stack.pop() + stack.pop());
        }
        else if(arr[i] == '-'){
            var a = stack.peek();
            stack.pop();
            var b = stack.peek();
            stack.push(b - a);
        }
        else if(arr[i] == '*'){
            stack.push(stack.pop() * stack.pop());
        }
        else{
            var a = stack.peek();
            stack.pop();
            var b = stack.peek();
            stack.push(b / a);
        }
    }
    console.log(stack.pop());
}
var arr = [1,2,'+',3,4,'-','*'];
rePoland(arr);  

阶乘

function fac(num) {
    var factorial = 1,
                stack=new Stack();
    while(num>0){
        stack.push(num--);
    }
    while(!stack.isEmpty()){
        factorial*=stack.pop();
    }
    console.log(factorial);
}
fac(5);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值