Programming
Process: Use class to simulate the list implementation stack.:p
Full test program address: http://test.hightman.net/stack/stack_05.php
In the form can enter: (3+5)/2, such as the expression test, support () +-/*
The following is all code
<?php
/* =================== Program Description ==================== * *
/* Written by Minglian (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 POPs (& $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, $n 1, $n 2)
{
Switch ($OP)
{
Case ' + ': Return ($n 2 + $n 1);
Case '-': Return ($n 2-$n 1);
Case "*": Return ($n 2 * $n 1);
Case '/': Return ($n 2/$n 1);
}
}
Main program
$expression = Trim ($_post[' expression ']);
if (empty ($expression))
{
Print <<<__eof__
<form method= "POST" >
Please input the inorder expression:
<input type= "text" size= "name=" "Expression" >
<input type= "Submit" value= "Submit" >
</form>
__eof__;
Exit ();
}
$stack _op = NULL;
$stack _on = NULL;
$n 1 = $n 2 = 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, $n 1);
Pop ($stack _on, $n 2);
Pop ($stack _op, $op);
Push ($stack _on, Two_result ($op, $n 1, $n 2));
}
Pop ($stack _op, $op); Pop the ' ('
}
else {
while (Privority ($expression [$i]) <= privority ($stack _op->data))
{
Pop ($stack _on, $n 1);
Pop ($stack _on, $n 2);
Pop ($stack _op, $op);
Push ($stack _on, Two_result ($op, $n 1, $n 2));
}
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, $n 1);
Pop ($stack _on, $n 2);
Push ($stack _on, Two_result ($op, $n 1, $n 2));
}
$result = 0;
Pop ($stack _on, $result);
Print <<<__eof__
The expression {$expression} result is ' $result '
<form method= "POST" >
If you wan to try again, please input the inorder expression:
<input type= "text" size= "name=" "Expression" value= "$expression" >
<input type= "Submit" value= "Submit" >
</form>
__eof__;
?>