码迷,mamicode.com
首页 > 其他好文 > 详细

使用栈模拟递归过程

时间:2016-04-09 22:03:27      阅读:236      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!