请大牛讲解一下用栈实现递归的问题

stuman 2017-07-26 01:21:31
请大牛讲解一下用栈实现递归的问题,或者推荐个博客。百度搜到的都看不懂呀
...全文
234 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Moyiii 2017-07-28
  • 打赏
  • 举报
回复
递归在底层实现就是用栈,或者说活动记录的。核心就是,在你模拟递归的时候,核心是记录当前函数的信息,以便还原。给你写了一个简单的,你可以理解一下
#include <iostream>
#include <stack>
using namespace std;

int fab(int n)
{
    if (n <= 1)
        return 1;
    else
        return n * fab(n - 1);
}

int main()
{
    stack<int> records;
    int n;
    cin >> n;
    records.push(n);
    
    //栈顶为当前执行的函数,如果执行不了就把函数的信息压入栈,然后调用递归函数
    while (records.top() != 1)
    {
        int newTop = records.top();
        records.push(newTop - 1);
    }

    //退栈求结果
    int result = 1;
    while (!records.empty())
    {
        result *= records.top();
        records.pop();
    }

    cout << result << endl;
    return 0;
}

33,010

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧