Write a function in c that does statistics on a doubly linke

Write a function in c++ that does statistics on a doubly linked list. It should be a constant function that prints out the largest sum, smallest, total, and average. It should do all this in one function definition. It needs to traverse the list. Please explain and be clear. I will upvote clear answer. Thanks!
Write a function in c++ that does statistics on a doubly linked list. It should be a constant function that prints out the largest sum, smallest, total, and average. It should do all this in one function definition. It needs to traverse the list. Please explain and be clear. I will upvote clear answer. Thanks!

Solution

I am using the below node structure in the function.

struct node
{
int data;
struct node *next;
struct node *prev;
}*start;

// Function to print the statistics.
void printStatistics()
{   
struct node *q = start;
int cnt = 0;
   int total = 0;
  
   // Traverse through the list and get a count of the list elements and total of all the elements.
while (q != NULL)
{
q = q->next;
       total += q->data;
cnt++;
}
  
   // calculate the average.
   int average = total/cnt;
  
cout <<\"Sum of all the elements in the List are: \" << total <<endl;
   cout <<\"Average of all the elements in the List are: \" << average << endl;
  
   // To find the Largest sum.
   // look for all positive contiguous segments of the the list (max_ending_here is used for this).
   // To keep track of maximum sum contiguous segment among all positive segments use max_so_far.
   // For every positive sum we get, compare it with max_so_far and update max_so_far if it is greater than max_so_far.
  
   int max_so_far = 0, max_ending_here = 0;
  
   // Initialize q to the start of the list.
   q = start;
  
   // traverse until the list is not empty.
   while(q != NULL){
      
       max_ending_here = max_ending_here + q->data;
      
       if(max_so_far < max_ending_here)
           max_so_far = max_ending_here;
          
       if(max_ending_here < 0)
           max_ending_here = 0;
   }
  
   cout << \"Largest sum in the list is: \" << max_so_far << endl;
  
   // On similar lines, try for smallest sum..
   // If you face problem, let me know
   // Hint: for smallest sum, we should use dynamic programming.
  
}

 Write a function in c++ that does statistics on a doubly linked list. It should be a constant function that prints out the largest sum, smallest, total, and av
 Write a function in c++ that does statistics on a doubly linked list. It should be a constant function that prints out the largest sum, smallest, total, and av

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site