Last active
January 19, 2016 13:18
-
-
Save alimranahmed/48dab6e129d46502447f to your computer and use it in GitHub Desktop.
Stack - Data Structure using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implementation of Stack using PHP | |
* @author Al- Imran Ahmed | |
*/ | |
class Node{ | |
public $value; | |
public $next; | |
} | |
class Stack{ | |
private $element; | |
private $top; | |
/** | |
* check whether the stack is empty or not | |
* @return boolean | |
* public function isEmpty(){ return false; } ;stub | |
*/ | |
public function isEmpty(){ | |
return $this->top == null; | |
} | |
/** | |
* Remove an element form the stack | |
* @return $element | |
* public function pop(){ return 0; } ;stub | |
*/ | |
public function pop(){ | |
if(!$this->isEmpty()){ | |
$value = $this->top->value; | |
$this->top = $this->top->next; | |
return $value; | |
} | |
return null; | |
} | |
/** | |
* Insert an element on the stack | |
* @param $element | |
* public function push($value){ | |
*/ | |
public function push($value){ | |
$oldtop = $this->top; | |
$this->top = new Node(); | |
$this->top->value = $value; | |
$this->top->next = $oldtop; | |
} | |
} | |
/* | |
//Client code | |
$stack = new Stack(); | |
$stack->push(1); | |
$stack->push(2); | |
$stack->push(333); | |
$stack->push("end"); | |
while(!$stack->isEmpty()){ | |
echo $stack->pop()."\n"; | |
}*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment