find the standard deviation of all nodes in a linked list in swift

To find the standard deviation of all nodes in a linked list, you can follow the below steps:

  1. Traverse the linked list and calculate the mean of all nodes.
  2. Traverse the linked list again and calculate the sum of the squared differences between each node value and the mean.
  3. Divide the sum of squared differences by the total number of nodes in the linked list.
  4. Take the square root of the result obtained in the previous step to get the standard deviation.

Here's the Swift code to implement the above algorithm:

main.swift
class Node {
    var value: Double
    var next: Node?
    
    init(value: Double) {
        self.value = value
    }
}

func standardDeviation(_ head: Node?) -> Double {
    // Step 1: Calculate the mean
    var current = head
    var sum = 0.0
    var count = 0
    while current != nil {
        sum += current!.value
        count += 1
        current = current?.next
    }
    let mean = sum / Double(count)
    
    // Step 2: Calculate the sum of squared differences
    current = head
    var squaredDiffsSum = 0.0
    while current != nil {
        squaredDiffsSum += pow(current!.value - mean, 2)
        current = current?.next
    }
    
    // Step 3: Divide the sum by the total number of nodes
    let variance = squaredDiffsSum / Double(count)
    
    // Step 4: Take the square root of the variance to get the standard deviation
    return sqrt(variance)
}
876 chars
36 lines

You can call the standardDeviation function by passing the head of the linked list as an argument. It will return the standard deviation of all nodes in the linked list.

gistlibby LogSnag