本文总结了几个递归算法的应用场景。
先来热身:计算从1+2+….+100的值
#include<stdio.h>
int sum(int val)
{
if(val == 100)
return 100;
return val + sum(val+1);
}
int main(void)
{
sum(1);
return 0;
}
1.经典问题,斐波切纳数列解法
/***
题目:输出斐波那契数列的对应项的值。斐波那契数列:0,1,1,2,3,5,8,13.... 要求函数实现计算,如:fibo(0)输出0 ,fibo(4)则输出5
***/
#include<stdio.h>
int fibo(int m)
{
if(m < 2){
return m;
}
return fibo(m - 1) + fibo(m - 2);
}
int main(int argc,char * argv[])
{
int input;
while(1){
input = 0;
printf("Pls input a fibo number:");
scanf("%d",&input);
if(input < 0){
printf("you had input an invalid value,pls input a number no less than 0\n");
continue;
}
printf("The result is: %d\n",fibo(input));
}
return 0;
}
2. 实现单向链表翻转
typedef struct LinkListNode{
int num;
struct LinkListNode * pNext;
}T_Node;
T_Node * ReverseLinkList(T_Node * pHead)
{
T_Node *pCurHead, *pNext;
if(pHead == NULL)
return NULL;
if(pHead->pNext == NULL)
return pHead;
pCurHead = pHead;
pNext = pHead->pNext;
pHead = ReverseLinkList(pNext);
pNext->pNext = pCurHead;
pCurHead->pNext = NULL;
return pHead;
}