这个例子写的太多了,到处都是,不过作为自己的笔记还是贴出来,如果大家的数据结构教材上的代码调试不通的话,这个代码还是有点作用的^_^, 另外个人觉得这个例子也确实是递归的经典用途
,下面的代码参考了<<c程序设计的抽象思维>>
/**//********************************************************************
created: 2005/12/24
created: 24:12:2005 10:42
filename: hanoi.c
author: Liu Qi
purpose: hanoi problem
*********************************************************************/
#include <stdio.h>
#include <assert.h>
#define COUNT 3
/**//*===========================================================================
* Function name: MoveSingleDisk
* Parameter: start:从start柱子开始,移动到finish柱子
* Precondition: void
* Description: 如果只有一个盘子,直接从开始得那根柱子移动到结束得柱子就可以了
* Return value: void
* Author: Liu Qi, [12/24/2005]
===========================================================================*/
void MoveSingleDisk(char start, char finish)
{
printf("%c -> %c\n", start, finish);
}
/**//*===========================================================================
* Function name: MoveTower
* Parameter: count:number of disks, start:开始的那根柱子
* Precondition: count > 0
* Description: 将count个disk从start移动到finish,借助temp
* Return value: void
* Author: Liu Qi, [12/24/2005]
===========================================================================*/
void MoveTower(int count, char start, char finish, char temp)
{
assert( count > 0 );
if (count == 1)
{
MoveSingleDisk(start, finish);
}
else
{
MoveTower(count - 1, start, temp, finish);
MoveSingleDisk(start, finish);
MoveTower(count - 1, temp, finish, start);
}
}
int main(int argc, char *argv[])
{
MoveTower(COUNT, 'A', 'B', 'C');
return 0;
} 运行结果如下: