fork(2) download
  1. infix = '2*((3-5)*2)'
  2. postfix = Array.new
  3. stack = Array.new
  4. operator = {
  5. '(' => 0,
  6. '+' => 1,
  7. '-' => 1,
  8. '*' => 2,
  9. '/' => 2,
  10. }
  11.  
  12. def isdigit(c)
  13. /\d/ =~ c
  14. end
  15.  
  16. infix.each_char do |exp|
  17. if isdigit(exp)
  18. postfix << exp
  19. else # Operator
  20. loop do
  21. case exp
  22. when '('
  23. stack << exp
  24. break
  25. when ')'
  26. while stack[-1] != '('
  27. postfix << stack.pop
  28. end
  29. stack.pop
  30. break
  31. end
  32. if !stack.empty?
  33. while operator[stack[-1]] >= operator[exp]
  34. postfix << stack.pop
  35. if stack.empty?
  36. break
  37. end
  38. end
  39. end
  40. break
  41. end
  42. if exp != '(' && exp != ')'
  43. stack << exp
  44. end
  45. end
  46. end
  47.  
  48. while !stack.empty?
  49. postfix << stack.pop
  50. end
  51.  
  52. postfix.each do |exp|
  53. print "#{exp} "
  54. end
  55. print "\n"
  56.  
Success #stdin #stdout 0.02s 7468KB
stdin
Standard input is empty
stdout
2 3 5 - 2 * *