作者:手机用户2502904917 | 来源:互联网 | 2018-03-22 15:16
四则运算表达式(中缀表达式)转换为后缀表达式:
如中缀表达式9 + ( 3 - 1 ) * 3 + 10 / 2,对应的后缀表达式是9 3 1 - 3 * + 10 2 / +
PS:逻辑实现了,要下班了,代码有些乱,明天再来优化。
0){
$key = (count($stack) - 1);
if(in_array($stack[$key], array('+', '-', '*', '/'))){
if(checkPriority($str, $stack[$key]) != 1){
for($i=$key; $i>=0; $i--){
if($stack[$i] == '('){
break;
}
$newStrList .= $stack[$i] . ' ';
unset($stack[$i]);
$stack = array_values($stack);
}
$stack[] = $str;
}else{
$stack[] = $str;
}
}else{
$stack[] = $str;
}
}else{
$stack[] = $str;
}
}
/**
* 判断运算符的优先级
* @param $operatorA
* @param $operatorB
* @return A大于B返回1,A等于B返回0,A小于B返回-1
*/
function checkPriority($operatorA, $operatorB){
switch($operatorA){
case '+':
case '-':
if($operatorB == '+' || $operatorB == '-'){
return 0;
}else if($operatorB == '*' || $operatorB == '/'){
return -1;
}
break;
case '*':
case '/':
if($operatorB == '+' || $operatorB == '-'){
return 1;
}else if($operatorB == '*' || $operatorB == '/'){
return 0;
}
break;
default:
exit('error');
}
}
$stack = array();
$newStrList = '';
$strList = '9 + ( 3 - 1 ) * 3 + 10 / 2';
$strList = explode(' ', $strList);
foreach($strList as $str){
if($str == ' '){
continue;
}
suffix($str, $stack, $newStrList);
}
$stack = array_reverse($stack);
foreach($stack as $s){
$newStrList .= $s . ' ';
}
echo $newStrList;