implement queue using linked list in php

Php program for implement queue using linked list. Here problem description and explanation.

<?php
/*
  Php Program for
  Implement queue using linked list
*/
// Create Q node
class QNode
{
	public $data;
	public $next;

	function __construct($value)
	{
		$this->data = $value;
		$this->next = NULL;
	}
}
class MyQueue
{
	public $head;
	public $tail;
	public $count;
	public	function __construct()
	{
		$this->head = NULL;
		$this->tail = NULL;
		$this->count = 0;
	}
	public	function size()
	{
		return $this->count;
	}
	public	function isEmpty()
	{
		return $this->count == 0;
	}
	// Add new node of queue
	public	function enqueue($value)
	{
		// Create a new node
		$node = new QNode($value);
		if ($this->head == NULL)
		{
			// Add first element into queue
			$this->head = $node;
		}
		else
		{
			// Add node at the end using tail 
			$this->tail->next = $node;
		}
		$this->count++;
		$this->tail = $node;
	}
	// Delete a element into queue
	function dequeue()
	{
		if ($this->head == NULL)
		{
			echo "Empty Queue", "\n";
			return -1;
		}
		// Pointer variable which are storing 
		// the address of deleted node
		$temp = $this->head;
		// Visit next node 
		$this->head = $this->head->next;
		$this->count--;
		if ($this->head == NULL)
		{
			// When deleting a last node of linked list
			$this->tail = NULL;
		}
		return $temp->data;
	}
	// Get front node
	public	function peek()
	{
		if ($this->head == NULL)
		{
			echo "Empty Queue", "\n";
			return -1;
		}
		return $this->head->data;
	}
	public static
	function main($args)
	{
		$task = new MyQueue();
		// Initially number of element
		echo "isEmpty : ".strval($task->isEmpty()), "\n";
		// Add element into queue
		$task->enqueue(10);
		$task->enqueue(20);
		$task->enqueue(30);
		$task->enqueue(40);
		$task->enqueue(50);
		// Test other function
		echo "size : ".strval($task->size()), "\n";
		echo "peek : ".strval($task->peek()), "\n";
		echo "dequeue : ".strval($task->dequeue()), "\n";
		echo "size : ".strval($task->size()), "\n";
		echo "peek : ".strval($task->peek()), "\n";
		echo "isEmpty : ".$task->isEmpty(), "\n";
	}
}
MyQueue::main(array());

Output

isEmpty : 1
size : 5
peek : 10
dequeue : 10
size : 4
peek : 20
isEmpty :


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