add a node to the beginning of a linked list in php

To add a new node to the beginning of a linked list in PHP, we can follow the below steps:

  1. Create a new node with the given data.
  2. Set its next pointer to point to the current head node of the linked list.
  3. Set the new node as the new head node of the linked list.

Here is the PHP code to add a new node at the beginning of a linked list:

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 push($data) {
        $newNode = new Node($data);
        $newNode->next = $this->head;
        $this->head= &$newNode;
    }

}

$linkedList = new LinkedList();
$linkedList->push(1);
$linkedList->push(2);
$linkedList->push(3);
493 chars
30 lines

In the above code, we created a Node class and a LinkedList class. The push method in the LinkedList adds a new node at the beginning of the linked list.

You can create a new node with your own data and call the push method to add it to the beginning of the linked list.

gistlibby LogSnag