递归与尾递归总结

一、递归node

  关于递归的概念,咱们都不陌生。简单的来讲递归就是一个函数直接或间接地调用自身,是为直接或间接递归。通常来讲,递归须要有边界条件、递归前进段和递归返回段。当边界条件不知足时,递归前进;当边界条件知足时,递归返回。用递归须要注意如下两点:(1) 递归就是在过程或函数里调用自身。(2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。算法

递归通常用于解决三类问题:
   (1)数据的定义是按递归定义的。(Fibonacci函数,n的阶乘)
   (2)问题解法按递归实现。(回溯)
   (3)数据的结构形式是按递归定义的。(二叉树的遍历,图的搜索)
递归的缺点:
  递归解题相对经常使用的算法如普通循环等,运行效率较低。所以,应该尽可能避免使用递归,除非没有更好的算法或者某种特定状况,递归更为适合的时候。 在递归调用的过程中系统为每一层的返回点、局部量等开辟了栈来存储,所以递归次数过多容易形成栈溢出。
  用线性递归实现Fibonacci函数,程序以下所示:
复制代码
1 int FibonacciRecursive(int n) 2 { 3 if( n < 2) 4 return n; 5 return (FibonacciRecursive(n-1)+FibonacciRecursive(n-2)); 6 }
复制代码

递归写的代码很是容易懂,彻底是根据函数的条件进行选择计算机步骤。例如如今要计算n=5时的值,递归调用过程以下图所示:函数

二、尾递归测试

  顾名思义,尾递归就是从最后开始计算, 每递归一次就算出相应的结果, 也就是说, 函数调用出如今调用者函数的尾部, 由于是尾部, 因此根本没有必要去保存任何局部变量. 直接让被调用的函数返回时越过调用者, 返回到调用者的调用者去。尾递归就是把当前的运算结果(或路径)放在参数里传给下层函数,深层函数所面对的不是愈来愈简单的问题,而是愈来愈复杂的问题,由于参数里带有前面若干步的运算路径。优化

  尾递归是极其重要的,不用尾递归,函数的堆栈耗用难以估量,须要保存不少中间函数的堆栈。好比f(n, sum) = f(n-1) + value(n) + sum; 会保存n个函数调用堆栈,而使用尾递归f(n, sum) = f(n-1, sum+value(n)); 这样则只保留后一个函数堆栈便可,以前的可优化删去。spa

  采用尾递归实现Fibonacci函数,程序以下所示:code

复制代码
1 int FibonacciTailRecursive(int n,int ret1,int ret2) 2 { 3 if(n==0) 4 return ret1; 5 return FibonacciTailRecursive(n-1,ret2,ret1+ret2); 6 }
复制代码

例如如今要计算n=5时的值,尾递归调用过程以下图所示:blog

从图能够看出,为递归不须要向上返回了,可是须要引入而外的两个空间来保持当前的结果。递归

  为了更好的理解尾递归的应用,写个程序进行练习。采用直接递归和尾递归的方法求解单链表的长度,C语言实现程序以下所示:ci

复制代码
 1 #include <stdio.h>
 2 #include <stdlib.h>  3  4 typedef struct node  5 {  6 int data;  7 struct node* next;  8 }node,*linklist;  9 10 void InitLinklist(linklist* head) 11 { 12 if(*head != NULL) 13 free(*head); 14 *head = (node*)malloc(sizeof(node)); 15 (*head)->next = NULL; 16 } 17 18 void InsertNode(linklist* head,int d) 19 { 20 node* newNode = (node*)malloc(sizeof(node)); 21 newNode->data = d; 22 newNode->next = (*head)->next; 23 (*head)->next = newNode; 24 } 25 26 //直接递归求链表的长度 27 int GetLengthRecursive(linklist head) 28 { 29 if(head->next == NULL) 30 return 0; 31 return (GetLengthRecursive(head->next) + 1); 32 } 33 //采用尾递归求链表的长度,借助变量acc保存当前链表的长度,不断的累加 34 int GetLengthTailRecursive(linklist head,int *acc) 35 { 36 if(head->next == NULL) 37 return *acc; 38 *acc = *acc+1; 39 return GetLengthTailRecursive(head->next,acc); 40 } 41 42 void PrintLinklist(linklist head) 43 { 44 node* pnode = head->next; 45 while(pnode) 46  { 47 printf("%d->",pnode->data); 48 pnode = pnode->next; 49  } 50 printf("->NULL\n"); 51 } 52 53 int main() 54 { 55 linklist head = NULL; 56 int len = 0; 57 InitLinklist(&head); 58 InsertNode(&head,10); 59 InsertNode(&head,21); 60 InsertNode(&head,14); 61 InsertNode(&head,19); 62 InsertNode(&head,132); 63 InsertNode(&head,192); 64  PrintLinklist(head); 65 printf("The length of linklist is: %d\n",GetLengthRecursive(head)); 66 GetLengthTailRecursive(head,&len); 67 printf("The length of linklist is: %d\n",len); 68 system("pause"); 69 }
复制代码

程序测试结果以下图所示: