用栈取代函数递归

文章目录

\color{orange}{1.用栈实现汉诺塔问题}
\color{red}{2.用栈实现求斐波拉契数列第n项}
\color{green}{3.习题}
\color{pink}{4.Reference}

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

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


1

2

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

#include<iostream>
#include<stack>
using namespace std;

long fibr(int n,stack<int*>&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() {
    stack<int*>st;
    cout << " 第8个斐波拉契数是:" << fibr(7,st);
}

3.习题

3
#include<iostream>
#include<stack>
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<int*>&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)<<endl;
    stack<int*>mystack;
    cout << "数列的第" << n << "项是:";
    cout << st(n,mystack) << endl;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容