Beispiel #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();
 }
Beispiel #2
0
 /**
  * A reverse-polish calculator.
  * Reads RPN expression from the input stream
  * and writes the computed results on the output stream.
  * Uses a stack.
  * Recognizes single-digit numbers, * +, * and =.
  *
  * @param resource $in The input stream.
  * @param resource $out The output stream.
  */
 public function calculator($in, $out)
 {
     $stack = new StackAsLinkedList();
     while (($c = fgetc($in)) !== false) {
         if (ord($c) >= ord('0') && ord($c) <= ord('9')) {
             $stack->push(box(ord($c) - ord('0')));
         } elseif ($c == '+') {
             $arg2 = $stack->pop();
             $arg1 = $stack->pop();
             $stack->push(box($arg1->getValue() + $arg2->getValue()));
         } elseif ($c == '*') {
             $arg2 = $stack->pop();
             $arg1 = $stack->pop();
             $stack->push(box($arg1->getValue() * $arg2->getValue()));
         } elseif ($c == '=') {
             $arg = $stack->pop();
             fprintf($out, "%s\n", str($arg));
         }
     }
 }