求C语言汉诺塔源代码(递归和非递归)

递归算法是我前几天写的,非递归算法是刚找到的,包含递归和非递归。\x0d\递归算法:\x0d\#include \x0d\//递归求解汉诺塔问题\ x0d \ Voidhanoi (int n,char a,char b,char c,int * time)\ x0d \ { \ x0d \ if(n > = 1)\ x0d \ { \ x0d \ Hanoi(n-1,A,C,B,time);\x0d\ move(A,C);\ x0d \(* time)++;\x0d\ hanoi(n-1,B,A,C,time);\ x0d \ } \ x0d \ } \ x0d \/打印出每一步的路径\ x0d \ Voidmove (char a,char c)\ x0d \ { \ x0d \ printf(" % c-> % c \ n ",a,c);\ x0d \ } \ x0d \ \ x0d \ int main(void)\ x0d \ { \ x0d \ int n,time = 0;;\x0d\printf("请输入汉诺塔的盘数:");\x0d\scanf("%d ",& ampn);\ x0d \ printf("汉诺塔对% d盘的移动方法是:",n);\ x0d \ printf(" \ n ");\x0d\hanoi(n,' A ',' B ',' C ',& amp时间);\x0d\printf("移动了%d次\n ",时间);\ x0d \ system(" pause ");\ x0d \返回0;\ x0d \} \ x0d \ \非递归算法:\ x0d \ # include \ x0d \ # define maxstack 10/*堆栈的最大深度*/\ x0d \ x0d \ int c = 65438。/*表示当前移动步数的全局变量*/\x0d\\x0d\struct hanoi {/*存储hanoi塔的结构,包括盘数和三个盘的名称*/\ x0d \ int n;\x0d\char x,y,z。\ x0d \ };\ x0d \ x0d \ void move (char x,int n,char y)/* move函数,这意味着将磁盘从一个管脚移动到另一个*/\ x0d \ { \ x0d \ printf(" % d-& gt;%d来自% c-& gt;%c\n ",c++,n,x,y);\ x0d \} \ x0d \ void Hanoi (int n,char x,char y,char z)/*汉诺塔的递归算法*/\ x0d \ { \ x0d \ if(1 = = n)\ x0d \ move(。\x0d\else {\x0d\hanoi(n - 1,x,z,y);\x0d\move(x,n,z);\x0d\hanoi(n - 1,y,x,z);\ x0d \ } \ x0d \ } \ x0d \ \ x0d \ void push(struct Hanoi * p,int top,char x,char y,char z,int n)\x0d\{\x0d\p[top+1]。n = n-1;\x0d\p[top+1]。x = x\x0d\p[top+1]。y = y\x0d\p[top+1]。z = z\ x0d \ } \ x0d \ \ void un reverse _ Hanoi(struct Hanoi * p)/*汉诺塔的非递归算法*/\ x0d \ { \ x0d \ int top = 0;\ x0d \ \ x0d \ while(top & gt;= 0) {\x0d\while (p[top].n & gt1) {/*向左走到最后*/\ x0d \ push (p,top,p [top]。x,p [top]。z,p [top]。y,p [top]。n);\ x0d \ top++;\ x0d \} \ x0d \ if (p [top]。n = = 1) {/*叶节点*/\ x0d \ move (p [top])。x,1,p [top]。z);\ x0d \ top-;\ x0d \ } \ x0d \ if(top & gt;= 0) {/*向右移动一步*/\ x0d \ move (p [top]。x,p [top]。n,p [top]。z);\ x0d \ top-;\x0d\ push(p,top,p[top+1]。y,p[top+1]。x,p[top+1]。z,p[top+1]。n);\ x0d \ top++;\ x0d \ } \ x0d \ } \ x0d \ } \ x0d \ \ x0d \ int main(void)\ x0d \ { \ x0d \ int I;\x0d\printf("递归:\ n ");\x0d\hanoi(3,' x ',' y ',' z ');\x0d\printf("非递归:\ n ");\ x0d \ struct Hanoi p[MAXSTACK];\ x0d \ c = 1;\x0d\p[0]。n = 3;\x0d\p[0]。x = 'x ',p[0]。y = 'y ',p[0]。z = ' z\ x0d \ un reverse _ Hanoi(p);\ x0d \ \ x0d \ return 0;\x0d\}