正在加载图片...
第5章递归与广义表 else( Queen(i+1) ∥在第计1行安放皇后 colD=md[n+ij-1]=sd[i+J]=0: 90=0; ∥撤消第i行第j列的皇后 5-5已知f为单链表的表头指针,链表中存储的都是整型数据,试写出实现下列运算的递归 算法 (1)求链表中的最大整数。 (2)求链表的结点个数。 (3)求所有整数的平均值 【解答】 #include <iostream. h> ∥定义在头文件" Recurvelist h"中 class ListNode i ∥链表结点类 ∥结点数据 ∥结点指针 Listnode( const int item):data(item,link(NUL){}∥构造函数 ∥链表类 int Max( ListNode *f); int Num( ListNode *f); float Avg( ListNode *f, int& n) public: List(): first(NULL), current(NULL) ∥构造函数 ∥析构函数 ListNode newnode( const int item);∥创建链表结点,其值为iem void NewList( const int revalue ) ∥建立链表,以输入 revalue结束 void PrintList ( ∥输出链表所有结点数据 int GetMax(){ return max(frst);}∥求链表所有数据的最大值 int Getnum(){ return Num( first片;}∥求链表中数据个数 noat GetAvg(){ return Avg(fist);}/求链表所有数据的平均值 }; ListNode* List: NewNode( const int item)( ∥创建新链表结点 ListNode *newnode= new ListNode(item):第 5 章 递归与广义表 58 else { Queen ( i+1 ); //在第 i+1 行安放皇后 col[j] = md[n+i-j-1] = sd[i+j] = 0; q[i] = 0; //撤消第 i 行第 j 列的皇后 } } } 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);
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有