To find the average of all nodes in a linked list, iterate through every node in the linked list and calculate the sum of all nodes' values. Finally, divide the sum by the number of nodes in the list to get the average.
Here's the implementation in Swift:
main.swift409 chars21 lines
The findAverage
function takes a linked list as a parameter and returns the average of all nodes' values in the list. To handle the case when the list is empty, we add a guard statement at the beginning of the function. Then, we declare two variables sum
and nodeCount
for calculating the sum of all nodes' values and the number of nodes in the list, respectively. We initialize sum
and nodeCount
to 0.
In the while loop, we go through every node in the list and add its value to sum
, increment nodeCount
by 1 and update currentNode
to the next node in the list.
Finally, we calculate the average by dividing sum
by nodeCount
and return it as a Double.
gistlibby LogSnag