/*****************************************
** This program demonstrates an iterative
** and a recursive approach to defining
** the max function.
*****************************************/
#include <iostream>
#include <algorithm> // defines max and min for doubles!
using namespace std;
/*****************************************
** Struct def's and function prototypes
*****************************************/
struct Node
{
double data;
Node *next;
};
void add2front(double val, Node* &L);
// ITERATIVE VERSION OF MAX (assume L not empty!)
double max_i(Node* L);
// RECURSIVE VERSION OF MAX (assume L not empty!)
double max_r(Node* L);
/*****************************************
** MAIN
*****************************************/
int main()
{
// Get list of values from user
Node *L = 0;
double x;
while(cin >> x)
add2front(x,L);
// Print maximum using both iteration and recursion
cout << "Maximum (via iteration) is: "
<< max_i(L) << endl;
cout << "Maximum (via recursion) is: "
<< max_r(L) << endl;
return 0;
}
/*****************************************
** Function definitions
*****************************************/
// ITERATIVE VERSION OF MAX (assume L not empty!)
double max_i(Node* L)
{
double m = L->data;
for(Node *p = L->next; p != 0; p = p->next)
m = max(m,p->data);
return m;
}
// RECURSIVE VERSION OF MAX (assume L not empty!)
double max_r(Node* L)
{
if (L->next == 0)
return L->data;
else
return max(L->data,max_r(L->next));
}
void add2front(double val, Node* &L)
{
Node *T = new Node;
T->data = val;
T->next = L;
L = T;
}