Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Insert Node at the End of a Linked List
Next article icon

Program to find average of all nodes in a Linked List

Last Updated : 19 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++




// 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;
}
 
 

Java




// Java implementation to find the average of
// nodes of the Linked List
class GFG
{
     
/* A Linked list node */
static class Node
{
    int data;
    Node next;
};
 
// function to insert a node at the
// beginning of the linked list
static Node push(Node head_ref, int new_data)
{
    /* allocate node */
    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;
    return head_ref;
}
 
// Function to iteratively find the avg of
// nodes of the given linked list
static double avgOfNodes(Node head)
{
    // if head = null
    if (head == null)
        return -1;
 
    int count = 0; // Initialize count
    int sum = 0;
    double avg = 0.0;
 
    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
public static void main(String args[])
{
    Node head = null;
 
    // create linked list 7.6.8.4.1
    head=push(head, 7);
    head=push(head, 6);
    head=push(head, 8);
    head=push(head, 4);
    head=push(head, 1);
 
    System.out.println("Average of nodes = " + avgOfNodes(head));
}
}
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 implementation to find the average of
# nodes of the Linked List
class newNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.next = None
 
# function to insert a node at the
# beginning of the linked list
def push(node,data):
     
    ''' allocate node '''
    if (node == None):
        return (newNode(data))
     
    else:
        node.next = push(node.next, data)
        return node
 
# Function to iteratively find the avg of
# nodes of the given linked list
def avgOfNodes(head):
     
    # if head = NULL
    if (head == None):
        return -1
     
    count = 0 # Initialize count
    sum = 0
    avg = 0.0
 
    while (head != None):
        count += 1
        sum += head.data
        head = head.next
     
    # calculate average
    avg = sum / count
    return avg
 
# Driver Code
 
# create linked list 7.6.8.4.1
head = newNode(7)
push(head, 6)
push(head, 8)
push(head, 4)
push(head, 1)
print("Average of nodes = ",avgOfNodes(head))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
 
 

C#




// C# implementation to find the average
// of nodes of the Linked List
using System;
 
class GFG
{
     
/* A Linked list node */
public class Node
{
    public int data;
    public Node next;
};
 
// function to insert a node at the
// beginning of the linked list
static Node push(Node head_ref,
                 int new_data)
{
    /* allocate node */
    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;
    return head_ref;
}
 
// Function to iteratively find the avg of
// nodes of the given linked list
static double avgOfNodes(Node head)
{
    // if head = null
    if (head == null)
        return -1;
 
    int count = 0; // Initialize count
    int sum = 0;
    double avg = 0.0;
 
    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
public static void Main(String []args)
{
    Node head = null;
 
    // create linked list 7.6.8.4.1
    head=push(head, 7);
    head=push(head, 6);
    head=push(head, 8);
    head=push(head, 4);
    head=push(head, 1);
 
    Console.WriteLine("Average of nodes = " +
                           avgOfNodes(head));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
// javascript implementation to find the average of
// nodes of the Linked List    /* A Linked list node */
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    // function to insert a node at the
    // beginning of the linked list
    function push(head_ref , new_data) {
        /* allocate node */
var 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;
        return head_ref;
    }
 
    // Function to iteratively find the avg of
    // nodes of the given linked list
    function avgOfNodes(head) {
        // if head = null
        if (head == null)
            return -1;
 
        var count = 0; // Initialize count
        var sum = 0;
        var avg = 0.0;
 
var current = head; // Initialize current
        while (current != null) {
            count++;
            sum += current.data;
            current = current.next;
        }
 
        // calculate average
        avg =  sum / count;
 
        return avg;
    }
 
    // Driver Code
     
var head = null;
 
        // create linked list 7.6.8.4.1
        head = push(head, 7);
        head = push(head, 6);
        head = push(head, 8);
        head = push(head, 4);
        head = push(head, 1);
 
        document.write("Average of nodes = " + avgOfNodes(head));
 
// This code contributed by aashish1995
</script>
 
 
Output
Average of nodes = 5.2

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

Auxiliary Space: O(1)



Next Article
Insert Node at the End of a Linked List

V

VishalBachchas
Improve
Article Tags :
  • DSA
  • Linked List
  • Technical Scripter
  • maths-mean
  • Technical Scripter 2018
Practice Tags :
  • Linked List

Similar Reads

  • Find sum of even and odd nodes in a linked list
    Given a linked list, the task is to find the sum of even and odd nodes in it separately. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 Output: Even Sum = 12 Odd Sum = 16 Input: 5 -> 7 -> 8 -> 10 -> 15 Output: Even Sum = 18 Odd Sum = 27 Approach: Traverse the whole li
    6 min read
  • Find the balanced node in a Linked List
    Given a linked list, the task is to find the balanced node in a linked list. A balanced node is a node where the sum of all the nodes on its left is equal to the sum of all the node on its right, if no such node is found then print -1. Examples: Input: 1 -> 2 -> 7 -> 10 -> 1 -> 6 -
    8 min read
  • Sum of all distinct nodes in a linked list
    Given a linked list and it may consist of duplicate nodes. The task is to find the sum of non-duplicate nodes. Examples: Input: 1 -> 2 -> 1 -> 3 -> 4 -> 3 -> NULL Output: 6 2 and 4 are the only non-duplicate nodes and 2 + 4 = 6. Input: 1 -> 3 -> 1 -> 3 -> 1 -> 3 -
    7 min read
  • Program for Nth node from the end of a Linked List
    Given a Linked List of M nodes and a number N, find the value at the Nth node from the end of the Linked List. If there is no Nth node from the end, print -1. Examples: Input: 1 -> 2 -> 3 -> 4, N = 3Output: 2Explanation: Node 2 is the third node from the end of the linked list. Input: 35 -
    15 min read
  • Insert Node at the End of a Linked List
    Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end
    9 min read
  • Print nodes of linked list at given indexes
    Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
    15+ min read
  • Sum of the alternate nodes of linked list
    Given a linked list, the task is to print the sum of the alternate nodes of the linked list. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : 50 Alternate nodes : 1 -> 3 -> 17 -> 29 Input : 10 -> 17 -> 33 -> 38 -> 73 Output : 116 Alternat
    12 min read
  • Sum and Product of all Fibonacci Nodes of a Singly Linked List
    Given a singly linked list containing N nodes, the task is to find the sum and product of all the nodes from the list whose data value is a Fibonacci number. Examples: Input: LL = 15 -> 16 -> 8 -> 6 -> 13 Output: Sum = 21, Product = 104 Explanation: The list contains 2 fibonacci data val
    13 min read
  • Find extra node in the second Linked list
    Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
    7 min read
  • Deletion at end (Removal of last node) in a Linked List
    Given a linked list, the task is to delete the last node of the given linked list. Examples:   Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 3 -> 12 -> 15-> NULLOutp
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences