Recursive function

来源:互联网 发布:javaweb小项目源码 编辑:程序博客网 时间:2024/05/17 00:55

5-1 已知A[n]为整数数组,试写出实现下列运算的递归算法:

(1) 求数组A中的最大整数。

(2) n个整数的和。

(3) n个整数的平均值。

【解答】

#include <iostream.h>class RecurveArray { //数组类声明private: int *Elements; //数组指针 int ArraySize; //数组尺寸

int CurrentSize; //当前已有数组元素个数public :

RecurveArray ( int MaxSize =10 ) :

ArraySize ( MaxSize ), Elements ( new int[MaxSize] ){ }~RecurveArray ( ) { delete [ ] Elements; }void InputArray(); //输入数组的内容int MaxKey ( int n ); //求最大值int Sum ( int n ); //求数组元素之和

float Average ( int n ); //求数组元素的平均值

};

 

void RecurveArray :: InputArray ( ){ //输入数组的内容

cout << "Input the number of Array: /n";

for ( int i = 0; i < ArraySize; i++ ) cin >> Elements[i];

}

 

int RecurveArray :: MaxKey ( int n ) { //递归求最大值

if ( n == 1 ) return Elements[0];

int temp = MaxKey ( n - 1 );

if ( Elements[n-1] > temp ) return Elements[n-1];

else return temp;

}

 

int RecurveArray :: Sum ( int n ) { //递归求数组之和

if ( n == 1) return Elements[0];

else return Elements[n-1] + Sum (n-1);

}

 

float RecurveArray :: Average ( int n ) { //递归求数组的平均值

if ( n == 1) return (float) Elements[0];

else return ( (float) Elements[n-1] + ( n - 1) * Average ( n - 1 ) ) / n;

}

 

int main ( int argc, char* argv [ ] ) { int size = -1;

cout << "No. of the Elements : ";

while ( size < 1 ) cin >> size;

RecurveArray ra ( size );

ra.InputArray();

cout<< "/nThe max is: " << ra.MaxKey ( ra.MaxSize ) << endl;

cout<< "/nThe sum is: " << ra.Sum ( ra.MaxSize ) << endl;

cout<< "/nthe avr is: " << ra.Average ( ra.MaxSize ) << endl;

return 0;

}

 

5-5 已知f为单链表的表头指针, 链表中存储的都是整型数据,试写出实现下列运算的递归算法:

(1) 求链表中的最大整数。

(2) 求链表的结点个数。

(3) 求所有整数的平均值。

【解答】

#include <iostream.h> //定义在头文件"RecurveList.h"

class List;

class ListNode { //链表结点类

friend class List;

private:

int data; //结点数据

ListNode *link; //结点指针

ListNode ( const int item ) : data(item), link(NULL) { } //构造函数

};

class List { //链表类

private:

ListNode *first, current;

int Max ( ListNode *f );

int Num ( ListNode *f );

float Avg ( ListNode *f, int& n );

public:

List ( ) : first(NULL), current (NULL) { } //构造函数

~List ( ){ } //析构函数

ListNode* NewNode ( const int item ); //创建链表结点, 其值为item

void NewList ( const int retvalue ); //建立链表, 以输入retvalue结束

void PrintList ( ); //输出链表所有结点数据

int GetMax ( ) { return Max ( first ); } //求链表所有数据的最大值

int GetNum ( ) { return Num ( first ); } //求链表中数据个数

float GetAvg ( ) { return Avg ( first ); } //求链表所有数据的平均值

};

 

ListNode* List :: NewNode ( const int item ) { //创建新链表结点

ListNode *newnode = new ListNode (item);

return newnode;

}

 

void List :: NewList ( const int retvalue ) { //建立链表, 以输入retvalue结束

first = NULL; int value; ListNode *q;

cout << "Input your data:/n"; //提示

cin >> value; //输入

while ( value != retvalue ) { //输入有效

q

 

原创粉丝点击