/*用栈模拟斐波那契数列,实现非递归的过程*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType data[MAXSIZE];
int top; //用于栈顶指针
}Sqstack;
//顺序栈的初始化
Status InitSqstack(Sqstack * S)
{
S->top=-1;
return OK;
}
//输出
void Print(Sqstack * S)
{
for(int i=0;i<=S->top;i++)
{
printf("%d ",S->data[i]);
}
printf("\n");
}
//出栈操作
Status Pop(Sqstack * S,SElemType * e)
{
if(S->top==-1) //栈底
{
return ERROR;
}
*e=S->data[S->top];
S->top--;
return OK;
}
//进栈操作
Status Push(Sqstack * S,SElemType e)
{
if(S->top==MAXSIZE-1) //栈满
{
return ERROR;
}
S->top++; //栈顶指针增加1
S->data[S->top]=e;
return OK;
}
/*栈模拟斐波那契数列*/
Status Fibonacci(Sqstack * S,int n)
{
int a[3];
a[0]=0;
a[1]=1;
int result,DeElem;
for(int i=0;i<(n/3);i++)
{
a[2]=a[0]+a[1];
Push(S,a[0]);
a[0]=a[1]+a[2];
Push(S,a[1]);
a[1]=a[2]+a[0];
Push(S,a[2]);
}
a[2]=a[0]+a[1];
Push(S,a[0]);
if((n%3==0))
{
Pop(S,&DeElem);
result=DeElem;
}
a[0]=a[1]+a[2];
Push(S,a[1]);
if((n%3==1))
{
Pop(S,&DeElem);
result=DeElem;
}
a[1]=a[2]+a[0];
Push(S,a[2]);
if((n%3==2))
{
Pop(S,&DeElem);
result=DeElem;
}
return result;
}
int main()
{
Sqstack S;
int n;
InitSqstack(&S);
printf("请输入n的值:\n");
scanf("%d",&n);
int result=Fibonacci(&S,n);
printf("结果为:%d\n",result);
return 0;
}
用栈模拟斐波那契数列,实现非递归的过程
最新推荐文章于 2022-11-14 22:14:31 发布