Program to find average of all nodes in a Linked List

Given a singly linked list. The task is to find the average of all nodes of the given singly linked list.

Examples:

Input: 7->6->8->4->1
Output: 26
Average of nodes:
(7 + 6 + 8 + 4 + 1 ) / 5 = 5.2

Input: 1->7->3->9->11->5
Output: 6

Iterative Solution:

  1. Initialise a pointer ptr with the head of the linked list and a sum variable with 0.
  2. Start traversing the linked list using a loop until all the nodes get traversed.
  3. Add the value of current node to the sum i.e. sum += ptr -> data .
  4. Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .
  5. Divide sum by total number of node and Return the average.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the average of
// nodes of the Linked List
  
#include <bits/stdc++.h>
using namespace std;
  
/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};
  
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;
  
    /* put in the data */
    new_node->data = new_data;
  
    /* link the old list to the new node */
    new_node->next = (*head_ref);
  
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
  
// Function to iteratively find the avg of
// nodes of the given linked list
float avgOfNodes(struct Node* head)
{
    // if head = NULL
    if (!head)
        return -1;
  
    int count = 0; // Initialize count
    int sum = 0;
    float avg = 0.0;
  
    struct Node* current = head; // Initialize current
    while (current != NULL) {
        count++;
        sum += current->data;
        current = current->next;
    }
  
    // calculate average
    avg = (double)sum / count;
  
    return avg;
}
  
// Driver Code
int main()
{
    struct Node* head = NULL;
  
    // create linked list 7->6->8->4->1
    push(&head, 7);
    push(&head, 6);
    push(&head, 8);
    push(&head, 4);
    push(&head, 1);
  
    cout << "Average of nodes = " << avgOfNodes(head);
  
    return 0;
}

chevron_right


Output:

Average of nodes = 5.2

Time complexity : O(n)
Where n is equal to number of nodes.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : VishalBachchas