使用栈模拟递归过程

    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

 

posted @ 2016-04-09 21:25  绯乐  阅读(733)  评论(0编辑  收藏  举报