find the largest node in a linked list in php

To find the largest node in a linked list, we need to traverse through all the nodes in the list and keep track of the maximum value found so far. Here's a sample implementation in PHP:

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 add($data) {
        $node = new Node($data);

        if ($this->head == null) {
            $this->head = $node;
        } else {
            $current = $this->head;
            while ($current->next != null) {
                $current = $current->next;
            }
            $current->next = $node;
        }
    }

    function findMax() {
        $max = null;
        $current = $this->head;

        while ($current != null) {
            if ($max == null || $current->data > $max) {
                $max = $current->data;
            }
            $current = $current->next;
        }

        return $max;
    }
}

// Example usage
$list = new LinkedList();
$list->add(5);
$list->add(10);
$list->add(3);
$list->add(8);
echo $list->findMax(); // Output: 10
1033 chars
54 lines

In this implementation, we define a Node class to represent each node in the linked list with its data and next properties. We then define the LinkedList class with its head property, which represents the first node in the list.

The add method is used to add new nodes to the end of the list. The findMax method is used to traverse the list and find the maximum value in the list using a while loop. We initialize max variable to null and compare it with each node's data. If a node's data is greater than max, we update max to that value. Finally, we return the max value found in the list.

related categories

gistlibby LogSnag