汉诺塔c语言非递归程序,汉诺塔非递归算法C语言实现

#include#define CSZL 10

#define FPZL 10

typedef struct hanoi

{

int n;

char x,y,z;

}hanoi;

typedef struct Stack

{

hanoi *base,*top;

int stacksize;

}Stack;

int InitStack(Stack *S)

{

S->base=(hanoi *)malloc(CSZL*sizeof(hanoi));

if(!S->base)

return 0;

S->top=S->base;

S->stacksize=CSZL;

return 1;

}

int PushStack(Stack *S,int n,char x,char y,char z)

{

if(S->top-S->base==S->stacksize)

{

S->base=(hanoi *)realloc(S->base,(S->stacksize+FPZL)*sizeof(hanoi));

if(!S->base)

return 0;

S->top=S->base+S->stacksize;

S->stacksize+=FPZL;

}

S->top->n=n;

S->top->x=x;

S->top->y=y;

S->top->z=z;

S->top++;

return 1;

}

int PopStack(Stack *S,int *n,char *x,char *y,char *z)

{

if(S->top==S->base)

return 0;

else

{

S->top--;

*n=S->top->n;

*x=S->top->x;

*y=S->top->y;

*z=S->top->z;

return 1;

}

}

int EmptyStack(Stack *S)

{

if(S->base==S->top)

return 1;

else

return 0;

}

int i=1;

void Move(char x,char z)

{

printf("\n\n\t\t第%d部,从%c移到%c。",i++,x,z);

}

int main()

{

int n;

char x,y,z;

Stack *S;

S=(Stack *)malloc(sizeof(Stack));

if(!S)

return 0;

if(!InitStack(S))

return 0;

printf("\n\n\t\t请输入汉诺塔的初始盘子数量以及轴的名称:");

scanf("%d%c%c%c",&n,&x,&y,&z);

if(!PushStack(S,n,x,y,z))

return 0;

while(!EmptyStack(S))

{

if(!PopStack(S,&n,&x,&y,&z))

break;

if(n==1)

{

Move(x,z);

}

else

{

if(!PushStack(S,n-1,y,x,z))

break;

if(!PushStack(S,1,x,y,z))

break;

if(!PushStack(S,n-1,x,z,y))

break;

}

}

free(S->base);

S->base=NULL;

S->top=NULL;

S->stacksize=0;

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值