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

To find the range of all nodes in a linked list, you need to traverse the entire list and keep track of the minimum and maximum values. Here's a sample code that demonstrates how to iterate over a linked list and find the range of all nodes:

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

class LinkedList {
    public $head;
    
    public function __construct() {
        $this->head = null;
    }
    
    public function insert($data) {
        $newNode = new Node($data);
        
        if ($this->head == null) {
            $this->head = $newNode;
        } else {
            $temp = $this->head;
            while ($temp->next != null) {
                $temp = $temp->next;
            }
            $temp->next = $newNode;
        }
    }
    
    public function getRange() {
        $min = PHP_INT_MAX;
        $max = PHP_INT_MIN;
        
        $temp = $this->head;
        while ($temp != null) {
            $data = $temp->data;
            if ($data < $min) $min = $data;
            if ($data > $max) $max = $data;
            $temp = $temp->next;
        }
        
        return [$min, $max];
    }
}

// example usage
$list = new LinkedList();
$list->insert(1);
$list->insert(3);
$list->insert(2);
[$min, $max] = $list->getRange();
echo "Range: $min-$max" // Output: "Range: 1-3"
1179 chars
55 lines

In the getRange() method, we initialize $min and $max to the smallest and largest possible integer values in PHP, respectively. We then iterate over the list and update $min and $max every time we encounter a node with a smaller or larger value than the current values, respectively. Finally, we return an array containing the min and max values.

gistlibby LogSnag