# Insert node at end of linked list in php

Write a program which is create and add linked list node at the end (tail, last) position in php.

Suppose we are inserted the following (10, 20, 30 ,40 ,50) node in a sequence. ``````<?php
// Php Program for
// Insert linked list element at end position set A

// Linked list node
{
public \$data;
public \$next;
public function __construct(\$data)
{
\$this->data = \$data;
\$this->next = NULL;
}
}
class SingleLL
{
public function __construct()
{
}
// Add new node at the end of linked list
{
// Create new node
\$node = new LinkNode(\$value);
if (\$this->head == NULL)
{
}
else
{
// Find the last node
while (\$temp->next != NULL)
{
// Visit to next node
\$temp = \$temp->next;
}
// Add node at last position
\$temp->next = \$node;
}
}
// Display all Linked List elements
public
function display()
{
if (\$this->head != NULL)
{
while (\$temp != NULL)
{
// Display node value
echo("  ".\$temp->data);
// Visit to next node
\$temp = \$temp->next;
}
}
else
{
}
}
}

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

Time complexity of above program is O(n). We can optimize above algorithm using one extra pointer. Which is hold the reference of last node. Below are implementation of this logic.

``````<?php
// Php Program for
// Insert linked list element at end position set B

// Linked list node
{
public \$data;
public \$next;
public  function __construct(\$data)
{
\$this->data = \$data;
\$this->next = NULL;
}
}
class SingleLL
{
public \$tail;
public  function __construct()
{
\$this->tail = NULL;
}
// Add new node at the end of linked list
{
// Create a new node
\$node = new LinkNode(\$value);
if (\$this->head == NULL)
{
}
else
{
\$this->tail->next = \$node;
}
\$this->tail = \$node;
}
// Display linked list element
public  function display()
{
if (\$this->head == NULL)
{
return;
}
// 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();
// 10 → 20 → 30 → 40 → 50 → NULL
echo(" Linked List \n");
\$sll->display();
}
main();``````
`````` Linked List
10 → 20 → 30 → 40 → 50 → NULL``````

Time complexity of above program is O(1).

## Comment

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.