Reverse Polish expression computing recently found some interesting code programs from previous collections that are gradually ported to PHP for interested people to refer to PHPcode/*** reverse Polish expression calculation * infix to suffix **/functionpostfix ($ infix) {$ priority = array (// operator inverse Polish expression calculation
I recently found some interesting code from my previous favorites during data sorting.
Plan to gradually port them to PHP for reference
PHP code
/***** Inverse Polish expression calculation * infix to suffix **/function postfix ($ infix) {$ priority = array (// operator priority '+' => 1, '-' => 1, '*' => 2, '/' => 2, '(' => 0, ')' => 0 ,'. '=> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); $ stack = array (); // symbol stack $ data = array (); // value stack $ I = $ top = 0; $ last =-1; $ len = strlen ($ infix ); while ($ I <$ len) {switch ($ infix {$ I}) {case '(': array_unshift ($ stack, $ infix {$ I}); break; case '+': case '-': case '*': c Ase '/': if ($ t! = '') Array_unshift ($ data, $ t); $ t = ''; while ($ priority [$ stack [0]> = $ priority [$ infix {$ I}]) {postfix_callback (array_shift ($ stack), $ data );} array_unshift ($ stack, $ infix {$ I}); break; case ')': if ($ t! = '') Array_unshift ($ data, $ t); $ t =''; while ($ stack [0]! = '(') {Postfix_callback (array_shift ($ stack), $ data);} array_shift ($ stack); break; default: if ($ I> $ last + 1 & $ t! = '') {Array_unshift ($ data, $ t); $ t ='';} $ t. = $ infix {$ I}; $ last = $ I; break;} $ I ++;} while ($ stack) {postfix_callback (array_shift ($ stack ), $ data);} return $ data [0];}/*** postfix function * used to calculate the expression value **/function postfix_callback ($ ch, & $ data) {$ B = array_shift ($ data); switch ($ ch) {case '+': $ data [0] + = $ B; break; case '-': $ data [0]-= $ B; break; case '*': $ data [0] * = $ B; break; case '/': $ data [0]/= $ B; break ;}}
Test example
PHP code
echo postfix( '(2+3)*(3+4)' ); //out 35
------ Solution --------------------
Paste it back first
------ Solution --------------------
This is a good thing.
------ Solution --------------------
The front row occupies the seat, and the boss is awesome.
------ Solution --------------------
The front row occupies the seat, and the boss is awesome.