Given a linked list of floats, write a function to compute the average of the list of values
Expert Answer
#include <iostream>
using namespace std;
// Node class
class LinkedNode {
double data;
LinkedNode* next;
public:
LinkedNode() {};
void SetData(double aData) { data = aData; };
void SetNext(LinkedNode* aNext) { next = aNext; };
double Data() { return data; };
LinkedNode* Next() { return next; };
};
// List class
class List {
LinkedNode *head;
public:
List() { head = NULL; };
void Print();
void Append(double data);
void Delete(int data);
int sumOfNodes();
};
/**
* Print the contents of the list
*/
void List::Print() {
// Temp pointer
LinkedNode *tmp = head;
// No nodes
if ( tmp == NULL ) {
cout << “EMPTY” << endl;
return;
}
// One node in the list
if ( tmp->Next() == NULL ) {
cout << tmp->Data();
cout << ” –> “;
cout << “NULL” << endl;
}
else {
// Parse and print the list
do {
cout << tmp->Data();
cout << ” –> “;
tmp = tmp->Next();
}
while ( tmp != NULL );
cout << “NULL” << endl;
}
}
int List::sumOfNodes()
{
double sum = 0;
int i=1;
double Avg;
LinkedNode *currentPtr = head;
while( currentPtr != NULL)
{
sum = sum + currentPtr->Data();
currentPtr = currentPtr->Next();
Avg=sum/i;
i++;
}
cout<<“The Average is “<<Avg<<endl;
}
/**
* Append a node to the linked list
*/
void List::Append(double data) {
// Create a new node
LinkedNode* newNode = new LinkedNode();
newNode->SetData(data);
newNode->SetNext(NULL);
// Create a temp pointer
LinkedNode *tmp = head;
if ( tmp != NULL ) {
// Nodes already present in the list
// Parse to end of list
while ( tmp->Next() != NULL ) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->SetNext(newNode);
}
else {
// First node in the list
head = newNode;
}
}
int main()
{
// New list
List list;
list.Append(100.55);
list.Print();
list.Append(200.66);
list.Print();
list.sumOfNodes();
}
Output:
100.55 –> NULL
100.55 –> 200.66 –> NULL
The Average is 150.605