find the first node in a linked list in php

To find the first node in a linked list in PHP, you need to traverse the linked list from its head until you reach the first node. Here's an example code:

main.php
class ListNode {
    public $val = 0;
    public $next = null;

    function __construct($val) {
        $this->val = $val;
    }
}

class LinkedList {
    public $head = null;

    public function addNode($val) {
        $newNode = new ListNode($val);

        if ($this->head === null) {
            $this->head = $newNode;
        } else {
            $curNode = $this->head;

            while ($curNode->next !== null) {
                $curNode = $curNode->next;
            }

            $curNode->next = $newNode;
        }
    }

    public function getFirstNode() {
        return $this->head;
    }
}

$linkedList = new LinkedList();
$linkedList->addNode(1);
$linkedList->addNode(2);
$linkedList->addNode(3);

$firstNode = $linkedList->getFirstNode();
echo "The value of the first node is " . $firstNode->val; // outputs "The value of the first node is 1"
868 chars
41 lines

In this example, we first define two classes: ListNode and LinkedList. ListNode represents a node in the linked list, and LinkedList represents the linked list itself.

The addNode method of LinkedList adds a new node to the linked list by traversing to the end of the list and adding the new node after the last node (if the list is not empty).

The getFirstNode method simply returns the head of the list, which is the first node.

We then create a new instance of LinkedList, add three nodes to it, and retrieve the first node using getFirstNode. The value of the first node is then printed out.

gistlibby LogSnag