From 7d7933f198157659b0d333f015fdd42a8ce15784 Mon Sep 17 00:00:00 2001 From: huruidong <1390095912@qq.com> Date: Fri, 12 Oct 2018 15:04:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9F=BA=E6=9C=AC=E7=9A=84=E5=9B=9B=E5=88=99?= =?UTF-8?q?=E8=BF=90=E7=AE=97=20+-*/()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- php/Stack/Compute.php | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 php/Stack/Compute.php diff --git a/php/Stack/Compute.php b/php/Stack/Compute.php new file mode 100644 index 00000000..3e5624bd --- /dev/null +++ b/php/Stack/Compute.php @@ -0,0 +1,78 @@ += 48 && ord($arr[$i] <= 57)){ + array_push($numStack, $arr[$i]); + continue; + } + switch ($arr[$i]){ + case '+': + case '-': + $arrLen = count($operStack); + while ($operStack[$arrLen-1] === '*' || $operStack[$arrLen-1] === '/' || $operStack[$arrLen-1] === '-'){ + compute($numStack, $operStack); + $arrLen--; + } + array_push($operStack, $arr[$i]); + break; + case '*': + case '/': + case '(': + array_push($operStack, $arr[$i]); + break; + case ')': + $arrLen = count($operStack); + while ($operStack[$arrLen-1] !== '('){ + compute($numStack, $operStack); + $arrLen--; + } + array_pop($operStack); + break; + default: + throw new \Exception("不支持的运算符", 1); + break; + } + } + + $arrLen = count($operStack); + while ($operStack[$arrLen-1] !== NULL){ + compute($numStack, $operStack); + $arrLen--; + } + echo array_pop($numStack); +} + +//数字栈长度减一,运算符栈长度减一 +function compute(&$numStack, &$operStack){ + $num = array_pop($numStack); + switch (array_pop($operStack)) { + case '*': + array_push($numStack, array_pop($numStack) * $num); + break; + case '/': + array_push($numStack, array_pop($numStack) / $num); + break; + case '+': + array_push($numStack, array_pop($numStack) + $num); + break; + case '-': + array_push($numStack, array_pop($numStack) - $num); + break; + + } +} +expression('-1+2-(1+2*3)'); +echo PHP_EOL; +eval('echo -1+2-(1+2*3);'); \ No newline at end of file