递归实验

144 阅读1分钟

第1关:递归创建链表

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
void CreatList(LinkList &p)
{    //递归创建链表
    int data;
    cin >> data;
    if(!data) return;
    p = new LNode;
    p->data = data;
    p->next = nullptr;
    CreatList(p->next);
}

第2关:递归从前向后输出链表

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
void Output(LinkList p)
{    //递归从前向后输出链表
 if(p == nullptr) return;
 cout << p->data << ' ';

    Output(p->next);
}

第3关:递归求解最大值

#include<iostream>
using namespace std;
typedef struct LNode
{
   int data;
   struct LNode *next;
}LNode,*LinkList;
int maxx = -2e9;
int GetMax(LinkList p)
{    //递归求解最大值
   if(p == nullptr) return maxx;
   if(maxx < p->data) maxx = p->data;
   GetMax(p->next);
   return maxx;
}

第4关:递归求解链表的结点个数

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
int ans = 0;
int GetLength(LinkList p)
{	//递归求解链表的结点个数
    if(p == nullptr) return 0;
    ans++;
    GetLength(p->next);
    return ans;
}

第5关:递归求解链表中所有整数的和

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
int sum = 0;
int GetSum(LinkList p)
{
    //递归求解链表中所有整数的和
    if(p == nullptr) return sum;
    sum += p->data;
    GetSum(p->next);
    return sum;
}

第6关:递归求解链表中所有整数的平均值

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
int sum = 0;
double GetAverage(LinkList p,int n)
{
    //递归求解链表中所有整数的平均值,n表示链表的结点个数
    if(p == nullptr) return 0;
    sum += p->data;
    GetAverage(p->next,n);
    return sum * 1.0 / n;
}

第7关:递归逆转链表

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
LinkList Reverse(LinkList head)
{
    LNode *cur = head, *pre = nullptr;
    while(cur != nullptr) {
        LNode* tmp = cur->next; // 暂存后继节点 cur.next
        cur->next = pre;           // 修改 next 引用指向
        pre = cur;                 // pre 暂存 cur
        cur = tmp;                 // cur 访问下一节点
    }
    return pre;

}