@PTA 数据结构 第二版 习题3.10 汉诺塔的非递归实现 (25分)
1、问题背景
汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
问题理解和递归思想
2、非递归的实现
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACKSIZE 100
//主要思想:较大环可以视为不存在
typedef struct{
char a;
char b;
char c;
int n;
}ElementType;
typedef struct node *PtrToSnode;
struct node{
ElementType *data;
int top;
int maxsize;
};
typedef PtrToSnode mystack;
mystack creatstack(int maxsize)
{
mystack ms = (mystack)malloc(sizeof(struct node));
ms->data = (ElementType *)malloc(maxsize * sizeof(ElementType));
ms->top = -1;
ms->maxsize = maxsize;
return ms;
}
void pushdata( mystack ms, ElementType x )
{
if( ms->top == ms->maxsize - 1)
{
printf("Stack is Full!\n");
}
else
{
ms->data[++(ms->top)] = x;
}
}
ElementType popdata( mystack ms )
{
if(ms->top == -1)
{
printf("Stack is Empty!\n");
}
else
{
return ms->data[ms->top--];
}
}
void hanoi( int n )
{
mystack ms = creatstack(STACKSIZE);
ElementType tmp,topush;
tmp.a = 'a';
tmp.b = 'b';
tmp.c = 'c';
tmp.n = n;
pushdata(ms, tmp);
while(ms->top != -1)
{
tmp = popdata(ms);
if(tmp.n == 1)
{
printf("%c -> %c\n",tmp.a,tmp.c);
}
else
{
//与递归的顺序相反,因为要按栈的顺序执行
topush.a = tmp.b;
topush.b = tmp.a;
topush.c = tmp.c;
topush.n = tmp.n - 1;
pushdata(ms, topush);
topush.a = tmp.a;
topush.b = tmp.b;
topush.c = tmp.c;
topush.n = 1;
pushdata(ms, topush);
topush.a = tmp.a;
topush.b = tmp.c;
topush.c = tmp.b;
topush.n = tmp.n-1;
pushdata(ms, topush);
}
}
}
int main()
{
int n;
scanf("%d",&n);
hanoi(n);
return 0;
}