递归的定义与使用

时间:2019-09-20
本文章向大家介绍递归的定义与使用,主要包括递归的定义与使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、定义是递归的:

(1)n!的递归实现:

递归方法:

public class Method {
    int fun(int n){
    if(n==1)
        return 1;
    else
        return(fun(n-1)*n);
    }
}
public class RecursionDemo {
    public static void main (String[] args){
      Method m=new Method();
      int num=m.fun(3);
      System.out.println(num);
    }
}

递归方法分析:

(1)该方法是直接递归,即自己调用自己。

例如:在执行fun(3)的时候,先执行fun(2)*3,而fun(2)=fun(1)*2,fun(1)=1。

(2)递归过程将问题的规模逐步缩小,参数的大小每次减1。一个个重复的过程,通过调用自身,减少了代码量。

(3)因为递归调用语句是在最后一句,因此,这种递归方式也称为尾递归。

2、数据结构是递归的:

       单链表的存储结构定义。

3、问题的求解是递归的:

#include<stdio.h> 
#include<malloc.h> 
#include<stdlib.h>
#define LIST_INIT_SIZE 100 
#define LISTINCREMENT 10
#define OVERFLOW -2
#define ERROR 0 
#define OK 1
typedef int ElemType; 

typedef struct{ //存储结构 
ElemType *elem; //指针类型 
int length; 
int listsize; 
}SqList;//顺序表的结构类型 

typedef int Status; 

Status InitList(SqList &L){         
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));//动态分配存储空间 
if(!L.elem) exit(OVERFLOW);  //分配失败退出 
L.length=0;                  //空表 
L.listsize=LIST_INIT_SIZE; //初始存储容量 
return OK; 
}

Status ListInsert(SqList &L,int i,ElemType e){//在第 i 个元素前插入一个新的元素e 
if(i<1 || i > L.length+1) return ERROR; //i值不合法 
if(L.length>=L.listsize) //存储空间不足 
{ 
ElemType * newbase=(ElemType *)realloc(L.elem,(LIST_INIT_SIZE+LISTINCREMENT)*sizeof(ElemType)); 
if(!newbase) exit(OVERFLOW); //分配失败 
L.elem=newbase; 
L.listsize=LIST_INIT_SIZE+LISTINCREMENT;
} 
for (int j=L.length; j>=i; --j)
L.elem[j]=L.elem[j-1]; 
L.elem[i-1]=e; 
L.length++;
return OK; 
}

Status ListEmpty(SqList L){ //判断顺序表是否为空
return L.length == 0; 
}

Status ListPrint(SqList &L) { 
printf(" 顺序表为: "); 
if (ListEmpty(L)) { 
printf(" 空。 \n"); 
return ERROR; 
} 
for (int i=0; i<L.length; ++i) 
{ 
printf("%-4d ", L.elem[i]); 
} 
printf("\n"); 
return OK; 
}

int Sum(SqList L,int i){

    if(i==L.length)
    return 0;
    else 
    return(L.elem[i]+Sum(L,i+1)); 
} 

main(){
    
SqList L; 
ElemType e; 
int i,j; 
InitList(L); 


printf(" 请输入你想创建的顺序表中元素的个数: "); 
scanf("%d",&i); 
if(i<1) printf(" 您输入的值有误,无法创建顺序表。 \n"); 
else 
{ 
printf(" 请您依次输入您想创建的顺序表的元素: "); 
for(j=1;j<=i;j++) 
{ 
scanf("%d",&e); 
ListInsert(L,L.length+1,e); //尾插 
} 
} 
ListPrint(L); //遍历顺序表 
int result=Sum(L,0);
printf( "顺序表所有元素的和为:%d",result);
}

这个程序是求解顺序表的元素的和,从顺序表的第一个元素开始,依次向后查找元素,并进行求和运算。

原文地址:https://www.cnblogs.com/zhai1997/p/11552938.html