一个非递归问题
议题提交:老师留的题如下:
f(m,n)= n+1 (m=0);时
f(m,n)=f(m-1,1) (n=0);时
f(m,n)=f(m-1,f(m,n-1)); (n!=0)时
要求用非递归算法编写程序求出当给定一组m,n的值时
fx的值
以下是我的答案:
问题: 我的程序已经调试通过
但是m和n 只能很小才行 请问 有没有办法改进?
方法1_用链栈实现非递归
#include <stdio.h>
#include <malloc.h>
typedef struct node
{int data;
struct node *next;
}stacknode,*linkstack;
linkstack top;
stacknode *g;
int m,n,fx,w;
linkstack init_linkstack()
{return NULL;}
int empty_linkstack(linkstack top)
{if(top==NULL) return 1;
else return 0;
}
linkstack push_linkstack(linkstack top,int x)
{stacknode *s;
s=malloc(sizeof(stacknode));
s->data=x; s->next=top; top=s;
return top;
}
linkstack pop_linkstack(linkstack top,int *x)
{stacknode *p;
if(top==NULL) return NULL;
else{*x=top->data; p=top; top=top->next;
free(p); return top;
}
}
pushf()
{
while(m)
{if(n==0)
{m--;n=1;}
else
{top=push_linkstack(top,m); /*这里如果只写push_linkstack(top,m);程序出错是为甚磨?*/
n--;
}
}
fx=n+1;
return;
}
popf()
{
top=pop_linkstack(top,&m); /*这里如果只写push_linkstack(top,m);程序出错是为甚磨?*/
m--;
n=fx;
printf("\n%d",m);
return;
}
main()
{
scanf("%d,%d",&m,&n);
do
{pushf();
if(top==NULL) break;
popf();
}while(1);
printf("\n %d,%d,%d",fx,m,n);
getch();
}
方法2_用数组标号模拟入栈出栈实现非递归
#include <stdio.h>
#include <malloc.h>
int con[10];
int m;
unsigned long fx;
unsigned long n;
pushf()
{
while(m)
{if(n==0)
{m--;n=1;}
else
{
con[m]++;
n--;
}
}
fx=n+1;
return;
}
popf()
{
int w,i;
for(i=1,w=0;w==0;i++)
if(con[i]!=0)
{m=i;
con[i]--;
w=1;
}
m--;
n=fx;
return;
}
main()
{
int j,k,mc;
scanf("%d,%d",&m,&n);
mc=m;
do
{pushf();
for(j=mc,k=0;k==0&&j>0;j--)
if(con[j]!=0) k=1;
if(k==0) break;
popf();
}while(1);
printf("\n\n fx=%lu",fx);
printf("\n\n n=%lu",n);
getch();
}