#ifndef PCH_H
#define PCH_H
//链表全整型数据,f为表头指针,使用递归算法
// TODO: 添加要在此处预编译的标头
#include<stdio.h>
#include<iostream>
#include<malloc.h>//free
#include<cstdlib>
#include<math.h>
#include<string>
#include<time.h>
constexpr auto MAXSIZE = 100;
constexpr auto OK = 1;
constexpr auto ERROR= 0;//宏
template<typename T>
constexpr auto random(T x) { return (rand()%x); }
/*随机生成一个在一定范围的数,宏定义中一个random(int number)函数*/
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;//链表
Status InitList(LinkList &f);//初始化链表
Status CreateList(LinkList &f,int j);//测试用
Status TravelList(LinkList f);
/*-------------------要求使用递归算法---------------------*/
int GetMax(LinkList f,int max);//求链表中的最大整数
int GetLength(LinkList f,int length);//求链表结点个数
double GetAverage(LinkList f,double sum,int c);//求所有整数的平均值
#endif //PCH_H
-----------------------------------------------------
// pch.cpp: 与预编译标头对应的源文件;编译成功所必需的
#include "pch.h"
// 一般情况下,忽略此文件,但如果你使用的是预编译标头,请保留它。
Status InitList(LinkList & f)
{
f = (LinkList)malloc(sizeof(LNode));//表头指针
if (!f) exit(OVERFLOW);
f->next = NULL;
return OK;
}
Status CreateList(LinkList & f,int j)
{
LNode *p;
p = f;
f->data = random(100);
srand((unsigned)time(0));
for(int i=0;i<j-1;i++)
{
p->next = (LinkList)malloc(sizeof(LNode));
p = p->next;
p->data = random(100);
p->next = NULL;
}
return OK;
}
Status TravelList(LinkList f)
{
LNode *p;
p = f;
while (p)
{
std::cout << p->data<<" ";
p = p->next;
}
return OK;
}
int GetMax(LinkList f,int max)
{
if (f==NULL)
return max;
else if (max<f->data)
{
max = f->data;
return GetMax(f->next, max);
}
else
{
return GetMax(f->next, max);
}
/*while (p->next)
{//循环算法
p = p->next;
if (p->data > max) max = p->data;
}*/
}
int GetLength(LinkList f,int length)
{
if (f==NULL) return length;
else
{
length++;
return GetLength(f->next, length);
}
/*循环算法
LNode *p;
p = f;
int count = 0;//计时器
while (p)
{
count++;
p = p->next;
}
return count;
*/
}
double GetAverage(LinkList f,double sum,int c)
{
if(f==NULL)
return sum/c;
sum +=f->data ;
c++;
return GetAverage(f->next,sum,c);
}
------------------------------------------------
// ConsoleApplication10.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
int main()
{
LinkList f;
InitList(f);
CreateList(f, 5);
TravelList(f);
std::cout<<"\n看,是最大值:"<<GetMax(f, -99999)<<"\n";
std::cout<<"看,是表长:"<<GetLength(f, 0)<<"\n";
std::cout<<"看,是平均值:"<<GetAverage(f, 0, 0);
}
求链表中最大整数结点个数平均值
最新推荐文章于 2022-09-28 19:32:28 发布
