各位高手帮我看看哪里有错误啊?我编译了没错,但是运行了之后就出错了,不知道什么原因啊?
题目是用非递归算法计算f(m,n),当m*n=0时,f(m,n)=m+n+1; 当m*n!=0时,f(m,n)=f(m-1,f(m,n-1));
下面是我编的程序:
#include<iostream>
using namespace std;
class Node
{ public: int mval,nval;
Node *next;
};
class Stack
{ private: Node *top;
public: void init(Stack &s,int m,int n){ s.top->next=NULL;s.top->mval=m;s.top->nval=n;}
// void init(int m,int n){top->next=NULL;top->mval=m;top->nval=n;}
/*void clear()
{ while(top->next!=NULL)
{ Node *p=top;
top=top->next;
delete p;
}
}*/
void push(Stack &s,int m,int n)
{ Node *p=new Node;
p->mval=m;
p->nval=n;
p->next=s.top;
s.top=p;
}
void pop(Stack &s){Node *p=s.top;s.top=p->next;delete p;}
/*void pop(Stack &s)
{ Node *p=s.top;
s.top=s.top->next;
delete p;
}*/
//int f(Stack &s,int m,int n);
int f(Stack &s ,int m,int n);
};
int Stack::f(Stack &s,int m,int n)
{
init(s,2,1);
//push(s,m,n);
do{ while(top->mval!=0)
{
{ while(s.top->nval!=0)
push(s,m,n-1);
}
if(s.top->next!=NULL && s.top->mval!=0 && s.top->nval==0)
{ s.top->next->mval=s.top->mval-1;
s.top->next->nval=s.top->mval+s.top->nval+1;
//s.top=s.top->next;
pop(s);
}
}
while(s.top->mval==0)
{ s.top->next->mval=s.top->mval;
s.top->next->nval=s.top->mval+s.top->nval+1;
pop(s);
}
} while(s.top->next!=NULL);
return s.top->mval+s.top->nval;
}
void main()
{ Stack s;
int m,n;
cout<<"输入m的值:";
cin>>m;
cout<<"输入n的值:";
cin>>n;
cout<<"f(m,n)="<<s.f(s,m,n)<<endl;
}