用class 模拟链表实现堆栈
--用PHP编程实现表达式的值。
/* =================== Program Description ==================== */
/* Written by MingLian Mar. (hightman) */
/* ============================================================ */
error_reporting(E_ALL & ~E_NOTICE);
if (!defined("NULL"))
define("NULL", 0);
class s_node
{
var $data = NULL;
var $next = NULL;
}
function push(&$stack, $value)
{
$newnode = new s_node;
$newnode->data = $value;
$newnode->next = $stack;
$stack = $newnode;
}
function pop(&$stack, &$value)
{
if ($stack != NULL)
{
$value = $stack->data;
$stack = $stack->next;
}
else
$value = -1;
}
function is_operator($op)
{
return strchr("+-*/()", $op);
}
function privority($op)
{
if ($op == ')' || $op == '(')
return 1;
else if ($op == '+' || $op == '-')
return 2;
else if ($op == '*' || $op == '/')
return 3;
else
return 0;
}
function two_result($op, $n1, $n2)
{
switch ($op)
{
case '+' : return ($n2 + $n1);
case '-' : return ($n2 - $n1);
case '*' : return ($n2 * $n1);
case '/' : return ($n2 / $n1);
}
}
// main program
$expression = trim($_POST['expression']);
if (empty($expression))
{
print <<<__EOF__
;
__EOF__;
exit();
}
$stack_op = NULL;
$stack_on = NULL;
$n1 = $n2 = 0;
$op = '';
$len = strlen($expression);
$tmp = '';
for ($i = 0; $i < $len; $i++)
{
if (is_operator($expression[$i]))
{
$tmp = trim($tmp);
if (!empty($tmp))
{
push($stack_on, $tmp);
$tmp = '';
}
if ($expression[$i] == '(' || empty($stack_op))
push($stack_op, $expression[$i]);
else if ($expression[$i] == ')')
{
while ($stack_op->data != '(')
{
pop($stack_on, $n1);
pop($stack_on, $n2);
pop($stack_op, $op);
push($stack_on, two_result($op, $n1, $n2));
}
pop($stack_op, $op); // pop the '('
}
else {
while (privority($expression[$i]) <= privority($stack_op->data))
{
pop($stack_on, $n1);
pop($stack_on, $n2);
pop($stack_op, $op);
push($stack_on, two_result($op, $n1, $n2));
}
push($stack_op, $expression[$i]);
}
}
else
$tmp .= $expression[$i];
}
$tmp = trim($tmp);
if (!empty($tmp))
{
push($stack_on, $tmp);
$tmp = '';
}
while (!empty($stack_op))
{
pop($stack_op, $op);
pop($stack_on, $n1);
pop($stack_on, $n2);
push($stack_on, two_result($op, $n1, $n2));
}
$result = 0;
pop($stack_on, $result);
print <<<__EOF__
The expression { $expression } result is '$result'。
__EOF__
?>
阅读(1141) | 评论(0) | 转发(0) |