コード例 #1
0
ファイル: index.php プロジェクト: Aisorfe/line_calculator
function get_polish_notation($expression)
{
    $current_op_stack = new Stack();
    $outstring = '';
    for ($i = 0; $i < strlen($expression); $i++) {
        if ($expression[$i] == ')') {
            while ($current_op_stack->top() != '(') {
                $outstring .= $current_op_stack->pop();
            }
            $current_op_stack->pop();
        }
        if ($expression[$i] == '(') {
            $current_op_stack->push($expression[$i]);
        }
        if ($expression[$i] == '-' or $expression[$i] == '+' or $expression[$i] == '*' or $expression[$i] == '/' or $expression[$i] == '^') {
            if ($current_op_stack->is_empty()) {
                $current_op_stack->push($expression[$i]);
            } elseif (spot_priority($expression[$i]) > spot_priority($current_op_stack->top())) {
                $current_op_stack->push($expression[$i]);
            } else {
                while (!$current_op_stack->is_empty() and spot_priority($current_op_stack->top()) >= spot_priority($expression[$i])) {
                    $outstring .= $current_op_stack->pop();
                }
                $current_op_stack->push($expression[$i]);
            }
        }
        if (is_numeric($expression[$i])) {
            $outstring .= '.';
            do {
                $outstring .= $expression[$i];
            } while (is_numeric($expression[++$i]));
            --$i;
        }
    }
    while (!$current_op_stack->is_empty()) {
        $outstring .= $current_op_stack->pop();
    }
    return $outstring;
}
コード例 #2
0
     * @param mixed $el Element to be pushed.
     * @return void.
     */
    public function push($el)
    {
        array_push($this->_data, $el);
    }
    /**
     * Pop the top element of the stack.
     *
     * @return mixed $element.
     */
    public function pop()
    {
        if ($this->top() !== null) {
            return array_pop($this->_data);
        }
        return null;
    }
}
// Example usage:
$stack = new Stack();
$stack->push("Element");
$stack->push(23);
$stack->push(array(3, 4, 6));
while (!$stack->is_empty()) {
    var_dump($stack->top());
    $stack->pop();
}
// Outputs NULL
var_dump($stack->top());