从汉诺塔问题看 函数尾部递归的消除 (C语言版)
来源:互联网 发布:js调用摄像头拍照插件 编辑:程序博客网 时间:2024/05/31 19:51
汉诺塔 函数尾部递归的消除
费,因此在没有必要的情况下不宜用递归。有时我们可以用递归的思想来考虑问题,
然后通过某些方法来消除递归,而这里仅仅考虑当递归语句是函数中最后执行的语
句情况下的消除方法,即通过使用循环可以将递归改变为迭代。下面第一个程序是
stefzeus@163.com
************************************************************************************************/
/* Answer for Hanoi */
/* move() uses two recursion to solve the problem. */
#include <stdio.h>
#include <conio.h>
#include <dos.h>
void move(int ,int ,int ,int );
void main()
{
int disk;
clrscr();
while(1)
{
printf("How many disk do you move:");
scanf("%d",&disk);
putchar('/n');
if( disk<21 && disk >0 )
break;
else
printf("Warring:The disks are too more or too less,"
"please input again./n");
}
move(disk,1,3,2);
getch();
}
/* move:moves count disk from start to finish using
temp for temporary storage. uses two recursion */
void move(int disk,int start,int finish,int temp)
{
if(disk>0)
{
move(disk-1,start,temp,finish); /* firth recursion */
printf("move %dth from %d to %d./n/n",disk,start,finish);
/* sleep(1); */ /* delay make user can see the result */
move(disk-1,temp,finish,start); /* second recursion */
}
}
/****************************************************************************************************************/
/* Hanio Of Second Edition */
/* move() uses noly one recursion (get rid of recursion in the tail */
/* of function. ) */
#include <stdio.h>
#include <conio.h>
#include <dos.h>
void move(int ,int ,int ,int );
void main()
{
int disk;
clrscr();
while(1)
{
printf("How many disk do you move:");
scanf("%d",&disk);
putchar('/n');
if( disk<21 && disk >0 )
break;
else
{
printf("Warring:The disks are too more or too less,"
"please input again./n");
continue;
}
}
move(disk,1,3,2);
getch();
}
/* move:moves count disk from start to finish using
temp for temporary storage. uses one recursion. */
void move(int disk,int start,int finish,int temp)
{
int t;
while(disk>0)
{
move(disk-1,start,temp,finish); /* firth recursion */
printf("move %dth from %d to %d./n/n",disk,start,finish);
sleep(1); /* delay make user can see the result */
disk--;
t=start;
start=temp;
temp=t;
}
}
- 从汉诺塔问题看 函数尾部递归的消除 (C语言版)
- 消除尾部递归
- 从汉诺塔问题看递归
- 从汇编的眼光看C++(之递归函数与模板类)
- 从汇编的眼光看C++(之递归函数与模板类)
- 从汇编的眼光看C++(之递归函数与模板类)
- 从汇编的眼光看C++(之递归函数与模板类)
- 八皇后问题 回溯递归 C语言版
- 从汇编的眼光看C++(之递归函数与模板类) ,(之泛型编程) .
- 二叉树的遍历(递归法)C语言版
- 经典递归应用--汉诺塔(C语言版)
- 数据结构(C语言版)-递归学习笔记
- 从汉诺塔问题看递归实质(用递归解决的两个小问题霍纳法则,排列问题)
- 皇后问题(c语言版)
- 递归调用实例分析2.在函数中间的递归与在函数尾部的递归
- Win32 SDK函数MessageBox的模拟实现(C语言版)
- C语言(10)--逻辑短路问题、显示安装进度、Bessel函数、消除多余的空格
- C语言版GetPrivateProfileString()函数,从初始化文件中指定的条目取得字串
- 《扩展和嵌入python解释器》2. 定义新类型
- java 乱码分析
- 最近发生了什么...
- SAP
- SOA
- 从汉诺塔问题看 函数尾部递归的消除 (C语言版)
- CoreJava day3
- REFER
- 用模板模式简化DAO操作Hibernate
- AVL树的构建----高度平衡树实现 (C语言实现)
- 数据库设计范式
- 对一个论坛系统的ER建模(精简版)
- 理解各种不同含义的new和delete
- MySQL的中文问题