递归算法,思路较为简单
int Ackerman(int m,int n)
{
if(m==0)
{
return n+1;
}
else if(m!=0&&n==0)
{
return Ackerman(m-1,1);
}
else
{
return Ackerman(m-1,Ackerman(m,n-1));
}
}
非递归算法,使用栈的思路解决问题
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define MAXSIZE 10000 /*顺序栈空间存储量*/
typedef int DataType;
typedef struct
{
DataType *s_m; /*顺序栈元素存储空间基址*/
DataType *s_n;
int top; /*栈顶*/
}SeqStack; /*顺序栈类型*/
/*初始化,构造一个空顺序栈*/
void InitSeqStack(SeqStack *S,int n)
{
S->s_m=(DataType *)malloc(n*sizeof(DataType));
S->s_n=(DataType *)malloc(n*sizeof(DataType));
if (S->s_m==NULL || S->s_n==NULL)
{
printf("\n内存分配失败\n");
exit(-1);
}
S->top=-1;
}
/*判断顺序栈是否为空,为空返回 1*/
int Empty_SeqStack(SeqStack *S)
{
if(S->top==-1)
{
return 1;
}
else
{
return 0;
}
}
/*判断栈是否为满,栈满返回 1*/
int Full_SeqStack(SeqStack *S)
{
if(S->top==MAXSIZE-1)
{
return 1;
}
else
{
return 0;
}
}
/*入栈,插入元素m,n为新的栈顶元素*/
int Push_SeqStack(SeqStack *S,DataType m,DataType n)
{
if(Full_SeqStack(S)==1)
{
printf("\n栈满,不能入栈\n");
return 0;
}
else
{
S->top++;
S->s_m[S->top]=m;
S->s_n[S->top]=n;
return 1;
}
}
/*出栈,删除栈顶元素*/
int Pop_SeqStack(SeqStack *S)
{
if(Empty_SeqStack(S))
{
return 0;
}
else
{
S->top--;
return 1;
}
}
/*取栈顶元素,由*m,*n返回其值*/
int GetTop_SeqStack(SeqStack *S,DataType *m,DataType *n)
{
if(Empty_SeqStack(S))
{
}
else
{
*m=S->s_m[S->top];
*n=S->s_n[S->top];
return 1;
}
}
/*非递归算法*/
int Ack(SeqStack *S,int m,int n)
{
int i,M,N;
int a,b;
Push_SeqStack(S,m,n);
while (Empty_SeqStack(S)==0)
{
GetTop_SeqStack(S,&M,&N);
if(M==0)
{
i=N+1;
Pop_SeqStack(S); /*符合该种情况直接出栈,用i表示该阿克曼函数*/
GetTop_SeqStack(S,&M,&N);
if(N==-1)
{
Pop_SeqStack(S); /*若b=-1,则说明上一个阿克曼函数的值为b*/
Push_SeqStack(S,M,i); /*进行出栈,入栈*/
}
}
else if(M!=0&&N==0)
{
Pop_SeqStack(S);
a=M-1,b=1;
Push_SeqStack(S, a, b); /*符合该种情况则先将旧的阿克曼函数出栈,将新的阿克曼函数入栈*/
}
else if(M!=0&&N!=0)
{
Pop_SeqStack(S);
a=M-1,b=-1;
Push_SeqStack(S,a,b); /*若b的值为一个阿克曼函数,则用-1表示*/
b=N-1;
Push_SeqStack(S,M,b); /*然后将新的阿克曼函数表示*/
}
}
return i;
}
int main()
{
SeqStack S;
int m,n,res;
int flag=1;
InitSeqStack(&S,MAXSIZE);
printf("请输入m和n的值:");
scanf("%d %d",&m,&n);
printf("\n");
res=Ack(&S,m,n);
printf("答案是:%d",res);
return 0;
}