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

To find the mode of all nodes in a linked list, we can implement an algorithm that performs counting of the nodes' values as we traverse through the linked list.

Here's a PHP function that takes a linked list and returns the mode of its values:

main.php
function findMode($head) {
    // initialize an empty array to store the count of each value
    $count = array();
    
    // traverse through the linked list
    while ($head != null) {
        $value = $head->data;
        
        // increment the count of the node's value
        if (isset($count[$value])) {
            $count[$value]++;
        } else {
            $count[$value] = 1;
        }
        
        $head = $head->next;
    }
    
    // find the mode (the value with the highest count)
    $mode = null;
    $maxCount = 0;
    foreach ($count as $value => $valueCount) {
        if ($valueCount > $maxCount) {
            $mode = $value;
            $maxCount = $valueCount;
        }
    }
    
    return $mode;
}
739 chars
31 lines

In this implementation, we first initialize an empty array to store the count of each node's value. We then traverse through the linked list, incrementing the count of each value as we encounter it. Finally, we find the mode (the value with the highest count) and return it.

Note that this algorithm has a time complexity of O(n), where n is the number of nodes in the linked list.

gistlibby LogSnag