Insert node at beginning of linked list in php

Write a program which is create and add new node at the beginning of linked list in php.

insert node at beginning of linked list

Here given of code implementation process.

<?php
/*
    Php program for
    Insert node at beginning of linked list
*/
// Linked list node
class LinkNode
{
    public $data;
    public $next;
    public  function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }
}
class SingleLL
{
    public $head;
    public  function __construct()
    {
        $this->head = NULL;
    }
    // Adding new node at beginning of linked list
    public  function addNode($data)
    {
        // Create new node
        $node = new LinkNode($data);
        // Connect current node to previous head
        $node->next = $this->head;
        $this->head = $node;
    }
    // Display linked list element
    public  function display()
    {
        if ($this->head == NULL)
        {
            return;
        }
        $temp = $this->head;
        // iterating linked list elements
        while ($temp != NULL)
        {
            echo(" ".$temp->data.
                " →");
            // Visit to next node
            $temp = $temp->next;
        }
        echo(" NULL\n");
    }
}

function main()
{
    $sll = new SingleLL();
    // Linked list
    // 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
    $sll->addNode(8);
    $sll->addNode(7);
    $sll->addNode(6);
    $sll->addNode(5);
    $sll->addNode(4);
    $sll->addNode(3);
    $sll->addNode(2);
    $sll->addNode(1);
    $sll->display();
}
main();
 Linked List
 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL

Time complexity of above program is O(1).



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved