递归公式的非递归实现(栈)
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef struct {
int data[MaxSize];
int top;
}SqStack;
void IniStack(SqStack& s) {
s.top = -1; //top指向的是栈顶元素,所以栈空时为-1,也可以让指针top指向下一个将要入栈的元素,小心上溢
}
bool IsEmpty(SqStack s) {
if (s.top == -1)
return true;
else
{
return false;
}
}
bool Push(SqStack& s, int x) {
if (s.top == MaxSize)
return false;
s.data[++s.top] = x;
return true;
}
bool Pop(SqStack& s, int& x) {
if (s.top == -1)
return false;
x = s.data[s.top--];
return true;
}
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;
}