如何将循环写成递归

转载:http://blog.csdn.net/feixiaoxing/article/details/6838362
编程

  其实编程的朋友知道,无论学什么语言,循环和递归是两个必须学习的内容。固然,若是循环还好理解一点,那么递归却没有那么简单。咱们曾经对递归讳莫如深,可是我想告诉你们的是,递归其实没有那么可怕。所谓的递归就是函数本身调用本身而已,循环本质上也是一种递归。数据结构

  

    1)求和递归函数函数

    咱们能够举一个循环的例子,前面咱们说过,若是编写一个1到n的求和函数怎么写呢,你可能会这么写:学习

int calculate(int m)
{
    int count = 0;
    if(m <0)
        return -1;

    for(int index = 0; index <= m; index++)
        count += index;
    
    return count;
}

上面只是一个示范。下面咱们看看若是是递归应该怎么写呢?spa

1 int calculate(int m)
2 {
3     if(m == 0)
4         return 0;
5     else
6         return calculate(m -1) + m;
7 }

    你们看着两段代码有什么不一样?.net

 

    (1)第一段代码从0,开始计算,从0到m逐步计算;第二段代码是从10开始计算,逐步到0以后这回,这样一样能够达到计算的效果指针

    (2)第一段代码不须要重复的压栈操做,第二段须要重复的函数操做,固然这也是递归的本质code

    (3)第一段代码比较长,第二段代码较短blog

 

   2)查找递归函数递归

    你们可能说,这些代码有些特殊。若是是查找类的函数,有没有可能修改为递归函数呢?

 1 int find(int array[], int length, int value)
 2 {
 3     int index = 0;
 4     if(NULL == array || 0 == length)
 5         return -1;
 6 
 7     for(; index < length; index++)
 8     {
 9         if(value == array[index])
10             return index;
11     }
12 
13     return -1;
14 }

你们可能说,这样的代码可能修改为这样的代码:

 1 int _find(int index, int array[], int length, int value)
 2 {
 3     if(index == length)
 4         return -1;
 5 
 6     if(value == array[index])
 7         return index;
 8 
 9     return _find(index + 1,  array, length, value);
10 }
11 
12 int find(int array[], int length, int value)
13 {
14     if(NULL == array || length == 0)
15         return -1;
16 
17     return _find(0, array, length, value);
18 }

    3) 指针变量遍历

 

    结构指针是咱们喜欢的遍历结构,试想若是有下面定义的数据结构:

1 typedef struct _NODE
2 {
3     int data;
4     struct _NODE* next;
5 }NODE;

那么,此时咱们须要对一个节点连接中的全部数据进行打印,应该怎么办呢?你们能够本身先想一想,而后看看咱们写的代码对不对。

 1 void print(const NODE* pNode)
 2 {
 3     if(NULL == pNode)
 4         return;
 5 
 6     while(pNode){
 7         printf("%d\n", pNode->data);
 8         pNode = pNode->next;
 9     }
10 }

 那么此时若是改为递归,那就更简单了:

1 void print(const NODE* pNode)
2 {
3     if(NULL == pNode)
4         return;
5     else
6         printf("%d\n", pNode->data);
7     
8     print(pNode->next);
9 }

其实,写这么多,就是想和你们分享一下我我的的观点:循环是一种特殊的递归,只有递归和堆栈是等价的。全部的递归代码均可以写成堆栈的形式,下面的一片博客咱们就讨论一下堆栈和递归的关系。要想写好,必须熟练掌握堆栈。

相关文章
相关标签/搜索