动态演示汉诺塔算法的实现过程
发布网友
发布时间:2022-05-20 19:40
我来回答
共2个回答
热心网友
时间:2023-11-18 08:38
C语言的书上有吧
记的以前学的时候看到过就是那本绿色的书
热心网友
时间:2023-11-18 08:39
// YUNA_2006_7_10
// The way to deal with hannio without digui
#include <iostream>
using namespace std;
#include <malloc.h>
// I will use a stuct to settle the problem
// the struct below is one point of the stuct
struct step
{
int counter; // the number of the disk
int begin; // the begin number
int temper; // the temp number
int end; // the end number
struct step *pre; // the pointer to point before
};
struct step *root = ( step * )malloc( sizeof( step ) ); // this is the end of the stuct
// fucion main begin here
int main()
{
step *temp = ( step * )malloc( sizeof( step ) ); // the temp to put data for temp
step *newstep; // the new step
step *top = root; // top is root in the first
cout << "Input the number of the disc:" << endl; // prompt
cin >> root->counter; // get the number of the disks
root->pre = NULL; // make the root`s data
root->begin = 1;
root->temper = 2;
root->end = 3;
// do part of a do/while
do
{
// when the disks` number is 1
if( top->counter == 1 ){
cout << top->begin << "to" << top->end << endl;
top = top->pre;
continue;
}
// put the top`s data into temp
temp->begin = top->begin;
temp->temper = top->temper;
temp->end = top->end;
temp->counter = top->counter;
// let the top become the first step
top->begin = temp->temper;
top->temper = temp->begin;
top->end = temp->end;
top->counter = temp->counter-1;
// push the secound step
newstep = ( step * )malloc( sizeof( step ) );
newstep->begin = temp->begin;
newstep->temper = temp->temper;
newstep->end = temp->end;
newstep->counter = 1;
newstep->pre = top;
top = newstep;
// push the third step
newstep = ( step * )malloc( sizeof( step ) );
newstep->begin = temp->begin;
newstep->temper = temp->end;
newstep->end = temp->temper;
newstep->counter = temp->counter-1;
newstep->pre = top;
top = newstep;
}while( top != NULL ); // end in top = root->pre
return 0;
} // end main
// 本程序只有一主函数,并没有使用递归
你能把我上面写的这个程序看懂你就知道汉诺塔是怎么动态实现的了