Last active
May 29, 2016 08:52
-
-
Save esase/e6edb71d219f3ed1b8baccc5325b3a88 to your computer and use it in GitHub Desktop.
Stack [data type]
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 | |
class Stack | |
{ | |
/** | |
* Items | |
* | |
* @var array | |
*/ | |
protected $items = []; | |
/** | |
* Items length | |
* | |
* @var integer | |
*/ | |
protected $itemsLength = 0; | |
/** | |
* Push | |
* | |
* @param mixed $value | |
* @return void | |
*/ | |
public function push($value) | |
{ | |
$this->itemsLength++; | |
$this->items[] = $value; | |
} | |
/** | |
* Pop | |
* | |
* @return mixed | |
* @throws Exception | |
*/ | |
public function pop() | |
{ | |
$lastItemIndex = $this->itemsLength - 1; | |
if ($lastItemIndex < 0) { | |
throw new Exception('There are no any items in stack'); | |
} | |
$value = $this->items[$lastItemIndex]; | |
unset($this->items[$lastItemIndex]); | |
$this->itemsLength--; | |
return $value; | |
} | |
} | |
$stack = new Stack(); | |
// fill the stack | |
foreach (range(0, 12) as $value) { | |
$stack->push($value); | |
} | |
// extract from the stack | |
foreach (range(0, 12) as $value) { | |
echo $stack->pop() . '<br>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment