已知head为单链表的表头指针,链表中存储的都是整型数据,实现下列运算的算法:
(1) 求链表中的最大值
(2)求链表中的结点个数
(3)求所有整数的平均值
#include<iostream>
#include<algorithm>
using namespace std;
class ListNode
{
public:
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//f(n)=max(f(n-1),an)
int getMax(ListNode* head, int Max)
{
if (head == NULL)
{
return Max;
}
else
{
return max(getMax(head->next, Max), head->val);
}
}
//f(n)=f(n-1)+1
int getSize(ListNode* head)
{
if (head == NULL)
{
return 0;
}
else
{
return(getSize(head->next) + 1);
}
}
//f(n)=(f(n-1)*(n-1)+an)/n
float getAverage(ListNode* head,int n)
{
if (head == NULL)
return 0;
else
{
return (float)(getAverage(head->next,n-1) * (n - 1) + head->val) / n;
}
}
};
递归法的实现思路:
与数学归纳法类似,先考虑f(n-1)与f(n)的关系,作为return的一般情况,再考虑临界值即n=1或0时的返回值,组合即可。