Ejemplo n.º 1
0
 /**
  * Parses a postfix expression read from the specified input stream
  * and constructs the corresponding expression tree.
  * The postfix expression consists of one-letter symbols,
  * one-digit numbers, +, -, * and /.
  *
  * @param resource $in The input stream.
  * @return object ExpressionTree An expression tree.
  */
 public static function parsePostfix($in)
 {
     $stack = new StackAsLinkedList();
     while (($c = fgetc($in)) != false) {
         if (ord('0') <= ord($c) && ord($c) <= ord('9') || ord('a') <= ord($c) && ord($c) <= ord('z') || ord('A') <= ord($c) && ord($c) <= ord('Z')) {
             $stack->push(new ExpressionTree($c));
         } elseif ($c == '+' || $c == '-' || $c == '*' || $c == '/') {
             $result = new ExpressionTree($c);
             $result->attachRight($stack->pop());
             $result->attachLeft($stack->pop());
             $stack->push($result);
         }
     }
     return $stack->pop();
 }