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.py944 chars46 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