用栈取代函数递归

文章目录




1.用栈实现汉诺塔问题:

DOMOVE相当于一步移动,
DOTOH相当于一次递归


1

2

2.用栈实现求斐波拉契数列第n项

#include
#include
using namespace std;

long fibr(int n,stack&S) {
    //result:the nth fibr
    long result=0;
    S.push(new int(n));
    //use loop to replace recursive
    while (S.empty() == false) {
        int* top = S.top();
        S.pop();
        if (*top <= 1) {
            result += 1;
        }
        else {
            S.push(new int(*top- 1));
            S.push(new int(*top-2));
        }
        delete top;
    }
    return result;
}

int main() {
    stackst;
    cout << " 第8个斐波拉契数是:" << fibr(7,st);
}

3.习题

3
#include
#include
using namespace std;

//store recursive states to reduce the time used.
long storestate[10000];
long recursive(int n){
    if (n <= 1)
        return 1;
    if (storestate[n] != 0)
        return storestate[n];
    storestate[(n + 1) / 2] = recursive((n + 1) / 2);
    storestate[n / 2] = recursive(n / 2);
    return storestate[(n + 1) / 2] + storestate[n / 2] + n;
}

long st(int n,stack&S) {
    //result:the nth number of the array.
    long result = 0;
    S.push(new int(n));
    while (S.empty() == false) {
        int* top = S.top();
        S.pop();
        if (*top <= 1)
            result++;
        else {
            S.push(new int((*top+1)/2));
            S.push(new int(*top / 2));
            result += *top;
        }
        //must free the space of place that the top points.
        delete top;
    }
    return result;
}
int main() {
    int n;
    cout << "输入数列的第几项:";
    cin >> n;
    cout << "数列的第" << n << "项是:";
    cout << recursive(n)<mystack;
    cout << "数列的第" << n << "项是:";
    cout << st(n,mystack) << endl;
}

你可能感兴趣的:(用栈取代函数递归)