递归与尾递归(tail-recursion)

转载于 https://blog.csdn.net/ywcpig/article/details/52749960

递归:

一般来说,递归需要有边界条件递归前进段递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。用递归需要注意以下两点:(1) 递归就是在过程或函数里调用自身。(2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。
递归一般用于解决三类问题:
  (1)数据的定义是按递归定义的。(Fibonacci函数,n的阶乘)
  (2)问题解法按递归实现。(回溯)
  (3)数据的结构形式是按递归定义的。(二叉树的遍历,图的搜索)
递归的缺点:
  递归解题相对常用的算法如普通循环等,运行效率较低。因此,应该尽量避免使用递归,除非没有更好的算法或者某种特定情况,递归更为适合的时候。在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储,因此递归次数过多容易造成栈溢出

在这里插入图片描述

尾递归:

顾名思义,尾递归就是从最后开始计算, 每递归一次就算出相应的结果, 也就是说, 函数调用出现在调用者函数的尾部, 因为是尾部, 所以根本没有必要去保存任何局部变量. 直接让被调用的函数返回时越过调用者, 返回到调用者的调用者去。尾递归就是把当前的运算结果(或路径)放在参数里传给下层函数,深层函数所面对的不是越来越简单的问题,而是越来越复杂的问题,因为参数里带有前面若干步的运算路径。
  尾递归是极其重要的,不用尾递归,函数的堆栈耗用难以估量,需要保存很多中间函数的堆栈。比如f(n, sum) = f(n-1) + value(n) + sum; 会保存n个函数调用堆栈,而使用尾递归f(n, sum) = f(n-1, sum+value(n)); 这样则只保留后一个函数堆栈即可,之前的可优化删去。

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

int FibonacciTailRecursive(int n,int ret1,int ret2){
   if(n==0)
       return ret1; 
   return FibonacciTailRecursive(n-1,ret2,ret1+ret2);
}

在这里插入图片描述
可以看出,尾递归不需要向上返回了,但是需要引入额外的两个空间来保持当前的结果。
或者如:

#include <stdio.h>
#include <stdlib.h>
 
typedef struct node
{
  int data;
  struct node* next;
}node,*linklist;
 
void InitLinklist(linklist* head)
{
     if(*head != NULL)
        free(*head);
     *head = (node*)malloc(sizeof(node));
     (*head)->next = NULL;
}
 
void InsertNode(linklist* head,int d)
{
     node* newNode = (node*)malloc(sizeof(node));
     newNode->data = d;
     newNode->next = (*head)->next;
     (*head)->next = newNode;
}
 
//直接递归求链表的长度 
int GetLengthRecursive(linklist head)
{
    if(head->next == NULL)
       return 0;
    return (GetLengthRecursive(head->next) + 1);
}
 
//采用尾递归求链表的长度,借助变量acc保存当前链表的长度,不断的累加 
int GetLengthTailRecursive(linklist head,int *acc)
{
    if(head->next == NULL)
      return *acc;
    *acc = *acc+1;
    return GetLengthTailRecursive(head->next,acc);
}
 
void PrintLinklist(linklist head)
{
     node* pnode = head->next;
     while(pnode)
     {
        printf("%d->",pnode->data);
        pnode = pnode->next;
     }
     printf("->NULL\n");
}
 
int main()
{
    linklist head = NULL;
    int len = 0;
    InitLinklist(&head);
    InsertNode(&head,10);
    InsertNode(&head,21);
    InsertNode(&head,14);
    InsertNode(&head,19);
    InsertNode(&head,132);
    InsertNode(&head,192);
    PrintLinklist(head);
    printf("The length of linklist is: %d\n",GetLengthRecursive(head));
    GetLengthTailRecursive(head,&len);
    printf("The length of linklist is: %d\n",len);
    system("pause");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值