<?php
class Stack {
private $stack_array = array();
public $index = -1;
public function __construct($array)
{
$this->stack_array = $array;
$length = count($this->stack_array);
$this->index = $length - 1;
}
public function print_array()
{
print_r($this->stack_array);
}
public function isEmpty()
{
if($this->index == -1){
return true;
}else{
return false;
}
}
public function push($element)
{
$this->index++;
$this->stack_array[$this->index] = $element;
}
public function pop()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
$element = $this->stack_array[$this->index];
unset($this->stack_array[$this->index]);
$this->index--;
}
}
public function pop_from_last()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
$element = $this->stack_array[0];
unset($this->stack_array[0]);
$this->index--;
return $element;
}
}
public function first()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
return $this->stack_array[$this->index];
}
}
public function last()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
return $this->stack_array[0];
}
}
public function get_element($position)
{
if($position >= $this->index + 1){
echo 'position is exceeding the array index';
}else{
$i = $this->index - ($position - 1);
return $this->stack_array[$i];
}
}
}
$stack = new Stack([3, 4, 5, 8]);
$stack->print_array();
echo $stack->index;
class Stack {
private $stack_array = array();
public $index = -1;
public function __construct($array)
{
$this->stack_array = $array;
$length = count($this->stack_array);
$this->index = $length - 1;
}
public function print_array()
{
print_r($this->stack_array);
}
public function isEmpty()
{
if($this->index == -1){
return true;
}else{
return false;
}
}
public function push($element)
{
$this->index++;
$this->stack_array[$this->index] = $element;
}
public function pop()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
$element = $this->stack_array[$this->index];
unset($this->stack_array[$this->index]);
$this->index--;
}
}
public function pop_from_last()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
$element = $this->stack_array[0];
unset($this->stack_array[0]);
$this->index--;
return $element;
}
}
public function first()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
return $this->stack_array[$this->index];
}
}
public function last()
{
if($this->isEmpty()){
echo 'The array doesn\'t contain any elemnet';
}else{
return $this->stack_array[0];
}
}
public function get_element($position)
{
if($position >= $this->index + 1){
echo 'position is exceeding the array index';
}else{
$i = $this->index - ($position - 1);
return $this->stack_array[$i];
}
}
}
$stack = new Stack([3, 4, 5, 8]);
$stack->print_array();
echo $stack->index;
No comments:
Post a Comment