栈的使用(JavaScript)

来源:互联网 发布:商家给淘宝开消费积分 编辑:程序博客网 时间:2024/06/01 10:39

从十进制转换成二进制

这里写图片描述

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);
0 0
原创粉丝点击