What is a suffix expression? The suffix expression, which refers to no parentheses, the operator is placed after the two operand, and all calculations are performed in the order in which the operators appear, strictly from left to right (the precedence rules of the operators are no longer considered). The PHP tutorial in this paper mainly uses examples to describe PHP implementation of stack-based suffix expression evaluation function. Share to everyone for your reference, as follows:
Implementation code:
<?phpclass stack{public $stack; Public $stack _top; Public Function __construct () {$this->stack=array (); $this->stack_top=-1; The public function push ($data) {$this->stack[]= $data; $this->stack_top++; Public Function Pop () {if (! $this->is_empty ()) {$this->stack_top--; Return Array_pop ($this->stack); }else {echo "stack is empty"; }} Public Function Is_empty () {if ($this->stack_top==-1) return true; }} $string = "1243-*+63/-"; $arrs =str_split ($string); Echo Var_export ($arrs); $stack =new Stack (); foreach ($arrs as $arr) { Switch ($arr) {case "+": $one = $stack->pop (); $two = $stack->pop (); $temp = $two + $one; $stack->push ($temp); Case "-": $one = $stack->pop (); $two = $stack->pop (); $temp = $two-$one; $stack->push ($temp); Case "*": $one = $stack->pop (); $two = $stack->pop (); $temp = $two * $one; $stack->push ($temp); Case "/": $one = $stack->pop (); $two = $stack->pop (); $temp = $two/$oNE; $stack->push ($temp); break; Default: $stack->push ($arr); }}echo $stack->pop ();? >
Operation Result:
Array (
0 = ' 1 ',
1 = ' 2 ',
2 = ' 4 ',
3 = ' 3 ',
4 = '-',
5 = ' * ',
6 = ' + ',
7 = ' 6 ',
8 = ' 3 ',
9 = '/',
Ten = '-',
) 1
After finishing this article, you must have a good understanding of the suffix expression, and also learned how to use PHP to implement a stack-based suffix expression evaluation function, this method is useful for programmers, later will introduce more relevant content and encourage everyone.
I hope this article is helpful to you in PHP programming.