题目:https://pintia.cn/problem-sets/434/problems/5892
借助堆栈以非递归(循环)方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。
输入格式:
输入为一个正整数N,即起始柱上的盘数。
输出格式:
每个操作(移动)占一行,按柱1 -> 柱2的格式输出。
输入样例:
3
输出样例:
a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c
代码:Inspired by (https://blog.csdn.net/royzdr/article/details/79032032)
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct node{
int pieces;
char start, medium, dst;
}ElemType;
ElemType ERROR = {0, 'a', 'b', 'c'};
typedef struct SNode{
ElemType Data[MAX_STACK_SIZE]; /*结构体数组*/
int Top;
int MaxSize;
}SNode, *Stack;
typedef enum{false, true} bool;
bool IsFull(Stack S);
bool IsEmpty(Stack S);
bool Push(Stack S, ElemType e);
ElemType Pop(Stack S);
void Hanoi(int N);
int main(void){
int N;
scanf("%d", &N);
Hanoi(N);
return 0;
}
bool IsFull(Stack S){
return (S->Top == S->MaxSize-1);
}
bool IsEmpty(Stack S){
return (S->Top == -1);
}
bool Push(Stack S, ElemType e){
if(IsFull(S)){
return false;
}
else{
S->Data[++(S->Top)] = e;
return true;
}
}
ElemType Pop(Stack S){
if(IsEmpty(S)){
return ERROR;
}
else{
return S->Data[(S->Top)--];
}
}
void Hanoi(int N){
Stack S = (Stack)malloc(sizeof(SNode));
S->Top = -1;
S->MaxSize = MAX_STACK_SIZE;
ElemType init={N, 'a', 'b', 'c'};
ElemType cur, temp;
Push(S, init);
while(!IsEmpty(S)){
cur = Pop(S);
if(cur.pieces>1){ /*先进后出*/
temp = cur;
temp.pieces--;
temp.start = cur.medium;
temp.medium = cur.start;
Push(S, temp); /*后:{N-1, 'b', 'a', 'c'}*/
temp = cur;
temp.pieces = 1;
Push(S, temp); /*再:{1, 'a', 'b', 'c'}*/
temp =cur;
temp.pieces--;
temp.medium = cur.dst;
temp.dst = cur.medium;
Push(S, temp); /*先:{N-1, 'a', 'c', 'b'}*/
}
else if(cur.pieces==1){
printf("%c -> %c\n", cur.start, cur.dst);
}
}
}