王道数据结构第96页第3题

题目要求:
在这里插入图片描述
参考了王道的书和视频,实现的代码如下:

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值