find the last node in a linked list in php

To find the last node in a linked list, you need to iterate through the list until you find the node whose next property is null. Here's a PHP function that does this:

main.php
function getLastNode($head) {
    $current = $head;
    while ($current !== null && $current->next !== null) {
        $current = $current->next;
    }
    return $current;
}
175 chars
8 lines

This function takes the head of the linked list as input and returns the last node in the list. It starts by setting a variable $current to the head of the list. Then it enters a loop that iterates through the list, one node at a time, by setting $current to its next property. The loop exits when $current is null or when $current's next property is null, which means $current is the last node in the list.

related categories

gistlibby LogSnag