Home  >  Article  >  Backend Development  >  逆波兰表达式计算,该如何解决

逆波兰表达式计算,该如何解决

WBOY
WBOYOriginal
2016-06-13 10:05:47814browse

逆波兰表达式计算
最近在整理资料时发现了一些以前收藏的有趣代码
计划逐步将他们移植到 PHP 供有兴趣的人参考

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->/** * 逆波兰表达式计算 * 中缀转后缀 **/function postfix($infix) {    $priority = array( //算符优先级        '+' => 1, '-' => 1,        '*' => 2, '/' => 2,        '(' => 0, ')' => 0,        '.' => 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0        );    $stack = array(); //符号栈    $data = array(); //数值栈     $i = $top = 0;    $last = -1;    $len = strlen($infix);    while($i= $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 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;    }}
测试例
PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->echo postfix( '(2+3)*(3+4)' ); //out 35


------解决方案--------------------
先回贴在看
------解决方案--------------------
这个好东西。

------解决方案--------------------
前排占座, 板主老大给力.
------解决方案--------------------
前排占座, 板主老大给力.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn