Insert node at middle of linked list in php
Suppose we are inserted the following (1, 2, 3, 4, 5, 6, 7) node in a sequence. In this post are implement second approach.

<?php
// Php Program for
// Insert linked list element at middle position
// Linked list node
class LinkNode
{
public $data;
public $next;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
}
class LinkedList
{
public $head;
// Class constructors
public function __construct()
{
$this->head = NULL;
}
// Insert node in middle position
public function insert($value)
{
// Create a new node
$node = new LinkNode($value);
if ($this->head == NULL)
{
// First node
$this->head = $node;
}
else
{
$temp = $this->head;
$middle = $this->head;
// Find the middle node
while ($temp->next != NULL && $temp->next->next != NULL)
{
$temp = $temp->next->next;
$middle = $middle->next;
}
// Add node
$node->next = $middle->next;
$middle->next = $node;
}
}
// Display linked list element
public function display()
{
if ($this->head == NULL)
{
return;
}
$temp = $this->head;
// iterating linked list elements
while ($temp != NULL)
{
printf("%s → ", $temp->data);
// Visit to next node
$temp = $temp->next;
}
printf("%s", "NULL\n");
}
public static function main($args)
{
$sll = new LinkedList();
// Add node
$sll->insert(1);
$sll->insert(2);
$sll->insert(3);
$sll->insert(4);
$sll->insert(5);
$sll->insert(6);
$sll->insert(7);
// 1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL
$sll->display();
}
}
LinkedList::main(array());
1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL
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