题目要求:
参考了王道的书和视频,实现的代码如下:
#include<stdio.h>
#define MaxSize 100
double P(int n,double x)
{
struct stack{
int no;
double val;
}st[MaxSize];
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()
{
double x;
int n;
printf("\n输入数n和x:\n");
scanf("%d%lf",&n,&x);
printf("\n计算结果为:\n%lf\n",P(n,x));
return 0;
}
王道所给的这个代码量不大,但理解起来不容易。
接下来我把这个算法基于链栈实现一下:(其实链栈也许更能体现出这个算法对于存储空间的节约)
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode{
int no;
double val;
struct LinkNode* next;
}LinkNode;
typedef LinkNode *LinkStack;
void InitStack(LinkStack &S)
{
S=(LinkStack)malloc(sizeof(LinkNode));
S->next=NULL;
}
void Push(int i,LinkStack &S)
{
LinkNode *p=(LinkNode*)malloc(sizeof(LinkNode));
p->next=S->next;
p->no=i;
S->next=p;
}
bool isEmpty(LinkStack S)
{
if(S->next)return false;
else return true;
}
bool Pop(LinkStack &S,int &no)
{
if(S->next==NULL)return false;
LinkNode *p=S->next;
no=p->no;
S->next=p->next;
free(p);
return true;
}
double P(int n,double x)
{
LinkStack S;
InitStack(S);
for(int i=n;i>=2;i--)
{
Push(i,S);
}
double fv0=1,fv1=2*x;
int no;
double v;
while(!isEmpty(S))
{
Pop(S,no);
v=2*x*fv1-2*(no-1)*fv0;
fv0=fv1;
fv1=v;
}
free(S);
return v;
}
int main()
{
double x;
int n;
printf("\n请输入数字n和x:\n");
scanf("%d%lf",&n,&x);
printf("\n计算结果为:\n%lf\n",P(n,x));
return 0;
}
判断算法是否正确,可与下面这个程序的运行结果比较:
#include<stdio.h>
int P(int x,int n)
{
if(n==0)
{
return 1;
}
else if(n==1)
{
return 2*x;
}
else if(n>1)
{
return 2*x*P(x,n-1)-2*(n-1)*P(x,n-2);
}
}
int main()
{
int x,n;
printf("\n输入n和x的值:\n");
scanf("%d%d",&n,&x);
printf("\n计算结果为:\n%d\n",P(x,n));
return 0;
}