Insert node at beginning of doubly linked list in php

Php program for Insert node at beginning of doubly linked list. Here problem description and other solutions.

<?php

// Php Program For
// insert new node at beginning of doubly linked list

// Define class of linked list Node
class LinkNode
{
	public $data;
	public $next;
	public $prev;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->next = NULL;
		$this->prev = NULL;
	}
}
class DoublyLinkedList
{
	public $head;
	public	function __construct()
	{
		$this->head = NULL;
	}
	// Insert new node at beginning position
	public	function insert($value)
	{
		// Create a node
		$node = new LinkNode($value);
		$node->next = $this->head;
		// When linked list is not empty
		if ($this->head != NULL)
		{
			$this->head->prev = $node;
		}
		// Make new head
		$this->head = $node;
	}
	// Display node element of doubly linked list
	public	function display()
	{
		if ($this->head == NULL)
		{
			printf("Empty Linked List\n");
		}
		else
		{
			printf("Doubly Linked List Element :\n");
			// Get first node of linked list
			$temp = $this->head;
			// iterate linked list 
			while ($temp != NULL)
			{
				// Display node value
				printf("%d  ",$temp->data);
				// Visit to next node
				$temp = $temp->next;
			}
		}
	}
	public static
	function main($args)
	{
		$dll = new DoublyLinkedList();
		// Insert following linked list nodes
		$dll->insert(70);
		$dll->insert(60);
		$dll->insert(50);
		$dll->insert(40);
		$dll->insert(30);
		$dll->insert(20);
		$dll->insert(10);
		//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
		$dll->display();
	}
}

DoublyLinkedList::main(array());

Output

Doubly Linked List Element :
10  20  30  40  50  60  70


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