将递归函数转化为非递归练习

来源:互联网 发布:淘宝培训 编辑:程序博客网 时间:2024/04/30 17:14

将递归函数转化为非递归练习

这是一个递归函数转化为非递归函数(模拟编译器行为,转化为goto风格的C code)的练习,纸上得来终觉浅,虽然原理比较简单,用一个栈,记录一些参数,但是自己写起来不好写,而且即使不考虑细节估计想一想也很困难。
上次写完Arkermann函数用了自己的理解写了写,思路不是很清晰,这回使用数据结构与算法书里的想法写了一写,写了fib函数,思路还算清晰,实现了递归函数转化为非递归,而且具有一般性。


#define LEN 10000#include<stdio.h>int stack[LEN][4],top=-1;//{n,f(n) or temp,label,solved} in stackvoid push(int n,int temp,int label){    top++;    stack[top][0]=n;    stack[top][1]=temp;    stack[top][2]=label;    stack[top][3]=0;    return;}void show(){    for (int i=0;i<=top;i++)        printf("%d %d %d %d\n",stack[i][0],stack[i][1],stack[i][2],stack[i][3]);    printf("---------------------------------------\n");     return;}int fib(int N){    int n;    if (N<2)        return N;    push(N,0,0);    label0:    //show();    if (stack[top][3])        switch (stack[top][2])        {            case 0:return stack[top][1];            case 1:goto label1;            case 2:goto label2;        }    n=stack[top][0];    if (n<2)    {        stack[top][1]=n;        stack[top][3]=1;        goto label0;    }    n=stack[top][0];    push(n-1,0,1);    goto label0;    label1:    stack[top-1][1]+=stack[top][1];    top--;    n=stack[top][0];    push(n-2,0,2);    goto label0;    label2:    stack[top-1][1]+=stack[top][1];    top--;    stack[top][3]=1;    goto label0;}int main(){    int n;    scanf("%d\n",&n);    printf("%d\n",fib(n));    return 0;}
0 0