#!/usr/bin/ruby class Stack def initialize() @stack = []; end def push(value) @stack.push(value) end def pop() @stack.pop() end def peek() @stack.last() end def empty?() @stack.empty?() end end while gets priority = {"*" => 2, "/" => 2, "+" => 1, "-" => 1, "(" => 0, ")" => 0} input = $_ output = "" stack = Stack.new() input.scan(/\d+|[\+\-\*\/\(\)]{1}?/).each{ |token| case token when "+","-","*","/" output << stack.pop() + " " while not stack.empty?() and priority[stack.peek()] >= priority[token] stack.push(token) when "(" stack.push("(") when ")" output << stack.pop() + " " until stack.peek() == "(" stack.pop() else output << token + " " end } output << stack.pop() + " " until stack.empty?() print output.strip + "\n" end