find the length of a linked list in php

To find the length of a linked list in PHP, we need to traverse the entire list and count the number of nodes.

Here's an example code that demonstrates how to find the length of a linked list in PHP:

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

    public function __construct($data = null) {
        $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) {
            $current = $this->head;
            while ($current->next !== null) {
                $current = $current->next;
            }
            $current->next = $newNode;
        } else {
            $this->head = $newNode;
        }
    }

    public function length() {
        $current = $this->head;
        $count = 0;
        while ($current !== null) {
            $count++;
            $current = $current->next;
        }
        return $count;
    }
}

// Usage:
$list = new LinkedList();
$list->insert(1);
$list->insert(2);
$list->insert(3);

echo "Length of the list is: " . $list->length(); // Output: Length of the list is: 3
1028 chars
49 lines

In this code, we create two classes, Node and LinkedList. The Node class represents a node in the linked list, which contains some data and a pointer to the next node. The LinkedList class maintains a reference to the head of the list and provides methods to insert new nodes into the list and find the length of the list.

The length() method of the LinkedList class traverses the entire list and counts the number of nodes. We start from the head of the list and keep moving forward until we reach the end of the list (pointed by null). At each node, we increment the counter variable $count. After traversing the entire list, we return the value of $count.

To use this code, we create a new LinkedList object, insert some nodes into it, and call the length() method to find the length of the list. In the example above, the output is Length of the list is: 3, which means the list contains three nodes.

gistlibby LogSnag