正在加载图片...
5-5已知f为单链表的表头指针,链表中存储的都是整型数据,试写出实现下列运算的递归 算法 (1)求链表中的最大整数。 (2)求链表的结点个数。 (3)求所有整数的平均值 【解答】 ∥定义在头文件" RecurveList h"中 class ListNode i ∥链表结点类 ∥结点数据 Listooder°lnk; ∥结点指针 Listnode( const int item):dao(lem,ink(NUL){}构造函数 ∥链表类 private ListNode first, current; int Max( listNode v; int Num( LisinNode v) noat Ag( ListNode f, int& n )i Lit(: firsT(NULl,cren(NULL){}∥构造函数 -List( ∥析构函数 Listnode* Ney node( const int iten);∥创建链表结点,其值为iem void New List const int revalue ) ∥建立链表,以输入 revalue结束 void PrintList ( 输出链表所有结点数据 int GetMax (return Max(first );1 求链表所有数据的最大值 int genU(){ return num(frst;}/求链表中数据个数 foat GetAg(return Ag(first )) ∥求链表所有数据的平均值 }; ListNode' List New Node( const int item )i ∥创建新链表结点 ListNode "newnode= new ListNode(item); return new node void List New List( const int revalue)( ∥建立链表,以输入 revalue结束 first= NULL; int value; ListNode g:6 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;
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有