非递归汉洛塔求助
为什么盘子数超过了2个以后就会直接闪掉啊!程序代码:
#include <stdio.h> #include <malloc.h> typedef struct list { int n; char x; char y; char z; }LIST; typedef struct zhan { LIST* top; LIST* base; }ZHAN; void init(ZHAN*l) { l->base=(LIST*)malloc(sizeof(LIST)*1000); l->base=l->top; } void push(ZHAN*l,int n,char x,char y,char z) { l->top->n = n; l->top->x = x; l->top->y = y; l->top->z = z; l->top++; } int pop(ZHAN*S,LIST*e) { if(S->base==S->top) { return -1; } else { S->top--; e->n = S->top->n; e->x = S->top->x; e->y = S->top->y; e->z = S->top->z; return 1; } } void move(char a,char c) { printf("将%c盘子移动到%c盘子\n",a,c); } void hanluota(int n,char x,char y,char z) { ZHAN l; init(&l); LIST p; push(&l,n,x,y,z); while (1==pop(&l,&p)) { if(p.n==1) { move(p.x,p.z); } else { push(&l,p.n-1,p.y,p.x,p.z); push(&l,1 ,p.x,p.y,p.z); push(&l,p.n-1,p.x,p.z,p.y); } } } int main(void) { int i; printf("请输入盘子的个数"); scanf("%d",&i); hanluota(i,'x','y','z'); getchar(); getchar(); return 0; }