#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const int maxlen=1000;
typedef struct node{ //工作记录结点
int adr; //返址
int np;
char xp,yp,zp; //值参
}snode;
typedef struct stack{ //定义栈
snode info[maxlen+1];
int top; //栈顶指针
}StackType;
StackType *STInit(){ //初始化栈
StackType *p;
if(p=new StackType){ //申请栈空间
p->top=0; //设置栈顶为0
return p; //返回栈顶指针
}
return NULL; //申请失败则返回NULL
}
void STClear(StackType *s){ //清空栈
s->top=0;
}
void STFree(StackType *s){ //释放空间
delete s; //使用delete释放用new运算符申请的内存空间
}
int STPush(StackType *s,snode inf){
if(s->top==maxlen){
cout<<"栈溢出"<<endl;
return 0;
}
s->info[++s->top]=inf;
return 1;
}
int STPop(StackType *s){
if(s->top==0){
cout<<"栈为空,不能再pop()!"<<endl;
return 0;
}
s->top--;
return 1;
}
snode *STTop(StackType *s){
if(s->top==0){
cout<<"栈为空,不能再top()!"<<endl;
exit(0);
}
return &(s->info[s->top]);
}
void move(char a,int x,char b){
cout<<"Move Disk"<<x<<" from "<<a<<" to "<<b<<"!
";
}
int main(){
int n;
char x,y,z;
StackType *s;
snode tmp1;
snode *curp; //当前栈顶记录
s=STInit(); //初始化栈
cout<<"Please enter the number of disk,ending with 0:";
while(cin>>n&&n){
x='x',y='y',z='z';
STClear(s); //清空栈,非递归入口
tmp1.adr=3;tmp1.np=n;tmp1.xp=x;tmp1.yp=y;tmp1.zp=z;
STPush(s,tmp1); //当前参量入栈
label0:
curp=STTop(s); //以curp代替栈顶记录
if(curp->np==1){
move(curp->xp,1,curp->zp);
switch(curp->adr){
case 1:goto label1;
case 2:goto label2;
case 3:goto label3;
}
}
tmp1.adr=1;tmp1.np=curp->np-1;tmp1.xp=curp->xp;tmp1.yp=curp->zp;tmp1.zp=curp->yp;
STPush(s,tmp1); //返址和下一层参量入栈
goto label0; //转向递归入口
label1:
STPop(s); //退栈,不是变参无须保存
curp=STTop(s);
move(curp->xp,curp->np,curp->zp);
tmp1.adr=2;tmp1.np=curp->np-1;tmp1.xp=curp->yp;tmp1.yp=curp->xp;tmp1.zp=curp->zp;
STPush(s,tmp1);
goto label0; //转向递归入口
label2:
STPop(s);
curp=STTop(s);
switch(curp->adr){
case 0:goto label0;
case 1:goto label1;
case 2:goto label2;
case 3:goto label3;
}
label3: //非递归出口
STPop(s);
cout<<"success!"<<endl;
}
STFree(s);
return 0;
}