out
。h
#pragma once
#include <iostream>
using namespace std;
typedef int ELemType;
//1. 创建无头结点的整型单链表;
typedef struct LinkList {
ELemType data;
LinkList* next;
}node,*pnode;
bool r_ini(pnode& R);
void r_creat(pnode& head);
void r_traverse(const pnode& R);
void r_rerverse(const pnode& current);
ELemType r_max(const pnode& s, ELemType& max);
int count(const pnode& s);
int ssum(const pnode& s);
。cpp
#include "recursionLL.h"
bool r_ini(pnode& R) {
//No Head
R = NULL;
return true;
}
/*
void r_creat(pnode& R) {//只考虑自然数
if (R == NULL) {
cout << "first node:";
pnode p = new node;
cin >> p->data;
p->next = NULL;
R = p;
}//为空时
pnode r = R;
while (r->next!=NULL) {
r = r->next;
}//rear
cout << "nodes:";
while (true) {
pnode p = new node;
cin >> p->data;
if (p->data < 0) {
delete p;
break;
}
p->next = NULL;
r->next = p;
r = p;//更新rear
}
}
*/
void r_creat(pnode& p) {//recursion
ELemType value;
cout << "请一次输入一个结点的值哈,输入负数将截止读取:";
cin >> value;
if (value< 0) {
//结束递归base step
return;
}
else {
p = new node;
p->data = value;
p->next = NULL;
//递归式创建
r_creat(p->next);
}
}
void r_traverse(const pnode& p) {//Recursion---traverse
if (p == nullptr ) {
return;
}
else {
//缩小范围,打印当前数据即可
cout << p->data << ' ';
//继续调用自己打印下一个
r_traverse(p->next);
}
}
void r_rerverse(const pnode& current) {//recursion
//先找关闭的条件.为空/走到表的尾巴
if (current == NULL) {
return ;
}
//一个一个反转的话,让current->next=pre successive
//pnode suc = current->next;//用于递归
//current->next = pre;//用于反转
else {
r_rerverse( current->next);
cout << current->data << ' ' ;
}
}
ELemType r_max(const pnode& s, ELemType& max) {
if (s != NULL) {
if (s->data > max) {
max = s->data;
}
else {
max = max;
}
return r_max(s->next, max);
}
}
int count(const pnode& s) {
pnode current = s;
int c = 0;
//先找关闭的条件.为空/走到表的尾巴
if (current == NULL) {
return 0;
}
//一个一个反转的话,让current->next=pre successive
//pnode suc = current->next;//用于递归
//current->next = pre;//用于反转
else {
while (current != NULL) {
current = current->next;
c++;
}
}
return c;
}
int ssum(const pnode& s) {
pnode current = s;
int sum = 0;
//先找关闭的条件.为空/走到表的尾巴
if (current == NULL) {
return 0;
}
else {
while (current != NULL) {
sum += current->data;
current = current->next;
}
}
return sum;
}
main
#include "recursionLL.h"
int main() {
//2 6 1 4 10 3 4 2 -1 9
pnode p;
r_ini(p);
r_creat(p);//递归式创建
cout << "Traverse:";
r_traverse(p);
cout << endl;
cout << "Reverse:";
pnode current = p;
r_rerverse(current);
cout << endl;
//get(max)
ELemType max =0;
r_max(p, max);
cout << "MAX=" << max << endl;
int c=count(p);
int sum =ssum(p);
cout << "count=" << c << endl;
float avg = float(sum) / c;
cout << "avg=" << avg << endl;
return 0;
}