find the variance of all nodes in a linked list in php

To find the variance of all nodes in a linked list in PHP, you can follow the below algorithm:

  1. First, calculate the mean of all the nodes in the linked list. To do this, traverse through the linked list and add the data value of each node to a variable. Then divide the sum by the total number of nodes to get the mean.

  2. Next, traverse through the linked list again and calculate the variance of each node. To do this, subtract the mean value obtained in step 1 from the data value of the node, square the difference and store it in a variable.

  3. Traverse through the linked list again and calculate the sum of all variances obtained in step 2.

  4. Finally, divide the sum obtained in step 3 by the total number of nodes in the linked list to get the variance of all nodes.

Here's the PHP code implementation:

main.php
class Node {
    public $data;
    public $next;
    
    function __construct($data) {
        $this->data = $data;
        $this->next = NULL;
    }
}

class LinkedList {
    public $head;
    
    function __construct() {
        $this->head = NULL;
    }
    
    function push($new_data) {
        $new_node = new Node($new_data);
        $new_node->next = $this->head;
        $this->head = $new_node;
    }
    
    function variance() {
        if ($this->head == NULL)
            return;
 
        $mean = 0;
        $size = 0;
        $current = $this->head;
        
        while ($current != NULL) {
            $mean += $current->data;
            $size++;
            $current = $current->next;
        }
        
        $mean /= $size;
 
        $variance = 0;
        $current = $this->head;
        
        while ($current != NULL) {
            $variance += pow(($current->data - $mean), 2);
            $current = $current->next;
        }
        
        return $variance / $size;
    }
}

//Example Usage
$llist = new LinkedList();
$llist->push(10);
$llist->push(20);
$llist->push(30);
$llist->push(40);

echo 'Variance of the linked list is: ' . $llist->variance();
1193 chars
60 lines

Output:

main.php
Variance of the linked list is: 125
36 chars
2 lines

gistlibby LogSnag