/** * Constructs a StackAsLinkedList_Iterator for the given stack. * * @param object StackAsLinkedList $stack A stack. */ public function __construct(StackAsLinkedList $stack) { parent::__construct(); $this->stack = $stack; $this->position = $stack->getList()->getHead(); $this->key = 0; }
/** * Main program. * * @param array $args Command-line arguments. * @return integer Zero on succes; non-zero on failure. */ public static function main($args) { printf("Demonstration program number 2.\n"); $status = 0; StackAsArray::main($args); StackAsLinkedList::main($args); QueueAsArray::main($args); QueueAsLinkedList::main($args); DequeAsArray::main($args); DequeAsLinkedList::main($args); return $status; }
/** * 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(); }
/** * 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)); } } }