implement stack using linked list in php

Php program for implement stack using linked list. Here problem description and other solutions.

<?php
// Php program for
// Implementation stack using linked list

// Stack Node
class StackNode
{
	public $data;
	public $next;
	public	function __construct($data, $top)
	{
		$this->data = $data;
		$this->next = $top;
	}
}
class MyStack
{
	public $top;
	public $count;
	public	function __construct()
	{
		$this->top = NULL;
		$this->count = 0;
	}
	// Returns the number of element in stack
	public	function size()
	{
		return $this->count;
	}
	public	function isEmpty()
	{
		if ($this->size() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	public	function push($data)
	{
		// Make a new stack node
		// And set as top
		$this->top = new StackNode($data, $this->top);
		// Increase node value
		$this->count++;
	}
	// Add a top element in stack
	public	function pop()
	{
		$temp = 0;
		if ($this->isEmpty() == false)
		{
			// Get remove top value
			$temp = $this->top->data;
			$this->top = $this->top->next;
			// Reduce size
			$this->count--;
		}
		return $temp;
	}
	// Used to get top element of stack
	public	function peek()
	{
		if (!$this->isEmpty())
		{
			return $this->top->data;
		}
		else
		{
			return 0;
		}
	}
}
class Test
{
	public static
	function main($args)
	{
		// Create new stack 
		$s = new MyStack();
		echo "\n Is empty : ",($s->isEmpty() == 1 ? "true" : "false"), "\n";
		// Add element
		$s->push(15);
		$s->push(14);
		$s->push(31);
		$s->push(21);
		$s->push(10);
		echo "\n Top  : ",$s->peek(), "\n";
		echo " Size : ",$s->size(), "\n";
		echo "\n Is empty : ",($s->isEmpty() == 1 ? "true" : "false"), "\n";
		// Delete Stack Element
		$data = $s->pop();
		echo "\n Pop element ",($data), "\n";
		echo " Size : ",($s->size()), "\n";
		$data = $s->pop();
		echo "\n Pop element ",($data), "\n";
		echo " Size : ",($s->size()), "\n";
	}
}
Test::main(array());

Output

 Is empty : true

 Top  : 10
 Size : 5

 Is empty : false

 Pop element 10
 Size : 4

 Pop element 21
 Size : 3


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