/*
使用递归和非递归方法实现递归函数计算
pn(x)=1, n=0
=2*x, n=1
=2*x*p(n-1)(x)-2*(n-1)p(n-2)(x), n>1
说明:
题目源自王道数据结构,P是书中参考答案给出的函数
*/
#include <iostream>
const int MAX=100;
using namespace std;
//递归方法
double P1(int n, double x){
if(n==0) return 1;
if(n==1) return 2*x;
return (2*x*P1(n-1,x) - 2*(n-1)*P1(n-2,x));
}
//非递归方法
double P2(int n, double x){
int num[100];
int i, top = 1;
num[0] = 1;
num[1] = 2*x;
if(n<0){
cout << "项数n不合法" << endl;
exit(0);
}else if(n<2){
return num[n];
}else{
for(i=2; i<=n; i++){
num[++top] = (2*x*num[top-1] - 2*(top-1)*num[top-2]);
}
return num[n];
}
}
double P(int n, double x){
struct stack{
int no;
double val;
}st[MAX];
int top = -1, i;
double fv1=1, fv2=2*x;
for(i=n; i>=2; i--){
top++;
st[top].no = i;
}
while(top>=0){
st[top].val = 2*x*fv2 - 2*(st[top].no-1)*fv1;
fv1 = fv2;
fv2 = st[top].val;
top--;
}
if(n==0){
return fv1;
}
return fv2;
}
int main(){
int i;
cout << "递归法: ";
for(i=0; i<10; i++)
cout << P1(i, 1) << " ";
cout << endl;
cout << "非递归法1:";
for(i=0; i<10; i++)
cout << P2(i, 1) << " ";
cout << endl;
cout << "非递归法2:";
for(i=0; i<10; i++)
cout << P(i, 1) << " ";
cout << endl;
return 0;
}
非递归实现递归函数(栈的应用)
最新推荐文章于 2023-11-24 16:29:44 发布