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

Here's an example function to find the sum of all nodes in a linked list in PHP:

main.php
class Node {
    public $data;
    public $next;
}

function getLinkedListSum($head) {
    $sum = 0;
    $current = $head;
    
    while ($current != null) {
        $sum += $current->data;
        $current = $current->next;
    }
    
    return $sum;
}
256 chars
17 lines

This function takes the head of a linked list as input and returns the sum of all nodes' data. It starts by initializing a sum variable to 0 and a current variable as the head of the list. It then loops through each node in the list, adding the value of its data property to the sum, and moving to the next node until it reaches the end of the list. Finally, it returns the sum.

gistlibby LogSnag