Wednesday, November 30, 2011

Stack implementation in PHP without array_push() and array_pop()

class Stack
{
const SIZE = 3;
private $a = array();
private $tos ; // Top of Stack

public function Stack($topOfStack){ // Constructor
$this->tos = $topOfStack;
}

public function push($value){
if(!self::isfull()){
echo '<br>Pushed to stack pos : ' .$this->tos;
$this->a[$this->tos++] = $value;
} else {
echo "<br>Stack overflow error (Stack size is " . self::SIZE . ")! Possible Data Loss !";
}
}

public function pop(){
if(!self::isempty()) {
echo '<br>Popped from stack pos : ' . ($this->tos - 1);
return($this->a[--$this->tos]);
} else {
echo "<br>Stack is empty! What to pop...!";
}
}

private function isempty() {
return ($this->tos == 0 ? 1 : 0 );
}

private function isfull() {
return ($this->tos == self::SIZE ? 1 : 0 );
}
};


$s = new Stack(0);
$s->push(100);
$s->push(200);
$s->push(300);
$s->push(400);
$s->pop();
$s->pop();
$s->pop();
$s->pop();

No comments:

Post a Comment