C语言不使用递归的方式实现汉诺塔
时间: 2024-01-27 22:03:54 浏览: 74
汉诺塔的非递归实现,c++
可以使用循环来实现汉诺塔,以下是示例代码:
```c
#include <stdio.h>
void hanoi(int n, char from, char to, char via);
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
hanoi(n, 'A', 'C', 'B');
return 0;
}
void hanoi(int n, char from, char to, char via) {
int i, j;
char stack[100], top = 0, temp;
while (1) {
while (n > 1) {
stack[top++] = to;
stack[top++] = from;
stack[top++] = via;
stack[top++] = n;
n--;
temp = to;
to = via;
via = temp;
}
printf("Move disk %d from %c to %c\n", n, from, to);
if (top == 0)
return;
n = stack[--top];
via = stack[--top];
from = stack[--top];
to = stack[--top];
printf("Move disk %d from %c to %c\n", n, from, to);
n--;
temp = from;
from = via;
via = temp;
}
}
```
该程序使用一个栈来保存每个递归调用的参数,然后使用循环来模拟递归调用。每次循环将当前参数压入栈中,然后将n减1并交换to和via,直到n为1时直接输出移动方案。当栈为空时,说明所有的递归调用已经完成,程序结束。
阅读全文