首页 > 其他 > 详细

使用栈模拟递归过程

时间:2016-04-09 22:02:04      阅读:205      评论:0      收藏:0      [点我收藏+]
    function Stack() {
        this.dataStore = [];
        this.top = 0;//top的值等同于数组内的元素个数   
        this.push = push;
        this.pop = pop;
    }
    function push(element) {
        this.dataStore[this.top++] = element;
    }
    function pop() {
        return this.dataStore[--this.top];
    }
    
    function fact(n) {
        var s = new Stack();
        while (n > 1) {
            s.push(n--);
        }
        var product = 1;
        while (s.top > 0) {
            product *= s.pop();
        }
        return product;
    }

    alert(fact(5)); // 显示 120

 

使用栈模拟递归过程

原文:http://www.cnblogs.com/feile/p/5372703.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!