Example of the stack data structure implemented by PHP [stack entry, stack exit, and stack traversal] and data structure example
This example describes the stack data structure implemented by PHP. We will share this with you for your reference. The details are as follows:
Using php Object-oriented thinking, the stack attributes include top, the maximum number of storage, and the storage container (the php array is used here ).
The Code is as follows: several methods are implemented for Stack entry, stack exit, and stack traversal:
<? Phpclass Stack {const MAXSIZE = 4; // maximum stack capacity: private $ top =-1; private $ Stack = array (); // use an array to store data public function _ construct () {$ this-> stack = array ();} // public function push ($ ele) on the inbound stack) {if ($ this-> top> = self: MAXSIZE-1) {echo 'stack is full... '; return false;} $ this-> stack [++ $ this-> top] = $ ele; // this Must Be ++ I, calculate and use} // The output stack, and return the public function pop () {if ($ this-> top =-1) of the stack element) {echo 'stack is empty... '; return false;} $ ele = $ this-> stack [$ this-> top]; unset ($ this-> stack [$ this-> top --]); // Here it must be I --, Which is used before calculation (note the difference between the output stack and the inbound stack) return $ ele;} // traverse the public function show () of the stack () {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 (); $ stack-> show ();
Running result:
43211