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

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.swift
func findAverage(in list: LinkedList<Int>) -> Double {
    var sum = 0
    var nodeCount = 0
    
    guard !list.isEmpty else {
        return 0
    }
    
    var currentNode = list.head
    
    while currentNode != nil {
        sum += currentNode!.value
        nodeCount += 1
        currentNode = currentNode!.next
    }
    
    let average = Double(sum) / Double(nodeCount)
    
    return average
}
409 chars
21 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