create a linked list in php

Below is an example code on how to create a simple linked list 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 push($data) {
        $newNode = new Node($data);
        $newNode->next = $this->head;
        $this->head = &$newNode;
    }

    function printList() {
        $temp = $this->head;
        while ($temp != NULL) {
            echo $temp->data . " ";
            $temp = $temp->next;
        }
    }
}

$list = new LinkedList();
$list->push(1);
$list->push(2);
$list->push(3);
$list->push(4);
$list->push(5);
$list->printList(); // Output: 5 4 3 2 1
716 chars
40 lines

In this example code, the Node class represents a node in the linked list. It has two properties: data to store the value of the node, and next to store the reference to the next node in the list.

The LinkedList class represents the linked list itself. It has one property: head, which refers to the first node in the list. It also has two methods: push() method to add a new node to the beginning of the list, and printList() method to print out the values of all nodes in the list.

To create a linked list, you first create a new instance of LinkedList. Then, you can add nodes to the list using the push() method. Finally, you can print out the values of all nodes using the printList() method.

gistlibby LogSnag