用栈模拟斐波那契数列,实现非递归的过程

来源:互联网 发布:onekeytools mac 编辑:程序博客网 时间:2024/06/16 10:42
/*用栈模拟斐波那契数列,实现非递归的过程*/#include<stdio.h>#include<stdlib.h>#include<time.h>#include<math.h>#define OK 1#define ERROR 0#define MAXSIZE 20typedef 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;}

运行结果

0 0
原创粉丝点击