infix    = '2*((3-5)*2)'
postfix  = Array.new
stack    = Array.new
operator = {
  '(' => 0,
  '+' => 1,
  '-' => 1,
  '*' => 2,
  '/' => 2,
}

def isdigit(c)
  /\d/ =~ c
end

infix.each_char do |exp|
  if isdigit(exp)
    postfix << exp
  else # Operator
    loop do
      case exp
      when '('
        stack << exp
        break
      when ')'
        while stack[-1] != '('
          postfix << stack.pop
        end
        stack.pop
        break
      end
      if !stack.empty?
        while operator[stack[-1]] >= operator[exp]
          postfix << stack.pop
          if stack.empty?
            break
          end
        end
      end
      break
    end
    if exp != '(' && exp != ')'
      stack << exp
    end
  end
end

while !stack.empty?
  postfix << stack.pop
end

postfix.each do |exp|
  print "#{exp} "
end
print "\n"
