find the smallest node in a linked list in php

To find the smallest node in a linked list in PHP, you can traverse the list and keep track of the minimum value seen so far. Here's an example implementation:

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

function findSmallestNode($head) {
    if ($head === null) {
        return null;
    }
    
    $minNode = $head;
    
    while ($head !== null) {
        if ($head->data < $minNode->data) {
            $minNode = $head;
        }
        $head = $head->next;
    }
    
    return $minNode;
}
457 chars
27 lines

In this implementation, we define a Node class to represent a node in the linked list. The findSmallestNode function takes the head of the linked list as input and returns the node with the smallest value.

We first handle the case where the linked list is empty by returning null. Otherwise, we initialize the minNode variable to the head of the list. We then traverse the list using a while loop, checking each node's data against the current minimum value. If we find a new minimum value, we update minNode to point to the current node. After we've traversed the entire list, we return minNode.

gistlibby LogSnag