PHP code/**
* 逆波兰表达式计算
* 中缀转后缀
**/
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
switch($infix{$i}) {
case '(':
array_unshift($stack, $infix{$i});
break;
case '+': case '-': case '*': case '/':
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 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;
}
}