Recommended: "PHP Video Tutorial"
1. Stack definition and knowledge
1. Definition: Stack, also known as stack or stack, is a special serial abstract data type in computer science. The special thing is that it is only allowed at one end of the linked list or array (the top of the stack Pointer, also known as "top") adds data push (push) and output data pop (pop stack). In addition, the stack can also be implemented using one-dimensional arrays and linked lists.
2. Characteristics of the stack:
a. First in, last out (last in, first out), that is to say, we can only add data by push at the top of the stack, and we can only Pop to delete data at the top of the stack;
b. Except for top (top of stack) and base (bottom of stack), every other element in the stack has a predecessor and successor;
2. Simple implementation of stack structure in php
<?php class HeapStack{ private $stackArr = array(); private $stackMaxTop = 10; // 栈顶最大值(用于控制栈长度,是否栈满) private $top = -1; // 栈顶(会随着push或pop的操作而变化) private $out; /** * 入栈 * */ public function pushValue($value='') { if(empty($value)) return '压入的值不能为空'; if($this->top == $this->stackMaxTop) return '栈内已满'; array_push($this->stackArr, $value); ++$this->top; return '入栈成功,栈顶值:'.$this->top; } /** * 出栈 * */ public function popValue() { if($this->top == -1) return '栈内没有数据'; $this->out = array_pop($this->stackArr); --$this->top; return '出栈成功,当前栈顶值:'.$this->top.'出栈值:'.$this->out; } /** * 获取栈内信息 */ public function getSatck() { return $this->stackArr; } public function __destruct() { echo 'over '; } } $stack = new HeapStack(); echo $stack->pushValue('stackValue')."\n"; echo $stack->pushValue('stackValue2')."\n"; var_dump($stack->getSatck()); echo $stack->popValue()."\n"; var_dump($stack->getSatck());
The above is the detailed content of Teach you how to implement stack structure using PHP. For more information, please follow other related articles on the PHP Chinese website!