Last active
August 29, 2015 14:23
-
-
Save thachp/17cc4864d57434d258d7 to your computer and use it in GitHub Desktop.
Stack implementation using array
This file contains hidden or 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 | |
/** | |
* Implement a stack using array. LIFO. No SPL. | |
* @author thachp | |
*/ | |
class Stack { | |
// dynamic type | |
private $_stack = array(); | |
// Move the first item in the array out. | |
public function pop($item) | |
{ | |
array_shift($this->_stack); | |
} | |
// Add item to the last item. | |
public function push($item) | |
{ | |
array_unshift($this->_stack, $item); | |
} | |
// get stack | |
public function getStack() | |
{ | |
return $this->_stack; | |
} | |
} | |
$stack = new Stack(); | |
$stack->push('a'); | |
$stack->push('b'); | |
$stack->push('c'); | |
// expect an array of c,b,a | |
print_r($stack->getStack()); | |
$stack->pop(); | |
// expect an array of b,a | |
print_r($stack->getStack()); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment