This article mainly introduces the PHP implementation of the stack data structure, combined with examples of PHP definition stack and into the stack, out of the stack, traversal stack and other related operations skills, the need for friends can refer to the next
This article describes the PHP implementation of the stack data structure. Share to everyone for your reference, as follows:
Using the object-oriented concept of PHP, the stack has the properties of top, maximum number of stores, and storage container (the PHP array is used here).
The code is as follows: Implements the stack, the stack, the traversal stack several methods:
<?phpclass stack{Const MAXSIZE = 4;//Stack maximum capacity private $top =-1; Private $stack = Array ();//use array to store data public function __construct () {$this->stack = array (); }//into the stack public function push ($ele) {if ($this->top >= self::maxsize-1) {echo ' stack was full ... '; return false; } $this->stack[++ $this->top] = $ele;//This must be ++i, first calculated and then used}//out of the stack, return the stack element public function pop () {if ($this top = =-1) {echo ' stack is empty ... '; return false; } $ele = $this->stack[$this->top]; unset ($this->stack[$this->top--]);//This must be i--, first use the recalculation (notice the difference between the stack and the stack) return $ele; }//Traverse stack public function show () {if ($this->top = =-1) {echo ' stack is empty ... '; return false; } for ($i = $this->top; $i >-1; $i-) {echo $this->stack[$i]. ' <br/> '; }}} $stack = new stack; $stack->push (1); $stack->push (2); $stack->push (3); $stack->push (4);//print_r ($ stack); $stack->show (); $a = $stack->pop (); $a = $Stack->pop (); $a = $stack->pop (); $stack->show ();
Operation Result:
43211
Articles you may be interested in:
Laravel tips for Query Builder How to add chain call method
PHP enables the sharing of Fibonacci sequence codes
PHP based on the binary method to implement array lookup function example explained