find the average of all nodes in a linked list in python

To find the average of all nodes in a linked list in python, we need to traverse the linked list and add the value of each node to a sum variable. We also need to keep track of the number of nodes in the linked list to calculate the average. Once we have the sum and the number of nodes, we can divide the sum by the number of nodes to get the average.

Here's the python code:

main.py
import math

class Node:
    def __init__(self, value=None):
        self.value = value
        self.next = None
        
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0
        
    def add_node(self, value):
        new_node = Node(value)
        
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        
        self.count += 1
        
    def average(self):
        if self.head is None:
            return 0
        
        sum = 0
        current = self.head
        
        while current is not None:
            sum += current.value
            current = current.next
            
        return sum / self.count
    
# Example usage:
ll = LinkedList()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)

print(ll.average()) # Output: 2.0
944 chars
46 lines

In this code, we first define the Node class that represents a single node in the linked list. It contains a value attribute and a next attribute that points to the next node in the linked list.

We then define the LinkedList class that contains the head and tail of the linked list, as well as a count variable that keeps track of the number of nodes in the linked list. The add_node method adds a new node to the linked list.

The average method calculates the average of all nodes in the linked list by traversing the linked list and adding up the value of each node to a sum variable. It then divides the sum by the count of nodes to get the average.

Finally, we create a new linked list, add some nodes to it, and call the average method to calculate the average of all nodes in the linked list. The code should output 2.0, which is the correct average for this example linked list.

gistlibby LogSnag