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"
aW5maXggICAgPSAnMiooKDMtNSkqMiknCnBvc3RmaXggID0gQXJyYXkubmV3CnN0YWNrICAgID0gQXJyYXkubmV3Cm9wZXJhdG9yID0gewogICcoJyA9PiAwLAogICcrJyA9PiAxLAogICctJyA9PiAxLAogICcqJyA9PiAyLAogICcvJyA9PiAyLAp9CgpkZWYgaXNkaWdpdChjKQogIC9cZC8gPX4gYwplbmQKCmluZml4LmVhY2hfY2hhciBkbyB8ZXhwfAogIGlmIGlzZGlnaXQoZXhwKQogICAgcG9zdGZpeCA8PCBleHAKICBlbHNlICMgT3BlcmF0b3IKICAgIGxvb3AgZG8KICAgICAgY2FzZSBleHAKICAgICAgd2hlbiAnKCcKICAgICAgICBzdGFjayA8PCBleHAKICAgICAgICBicmVhawogICAgICB3aGVuICcpJwogICAgICAgIHdoaWxlIHN0YWNrWy0xXSAhPSAnKCcKICAgICAgICAgIHBvc3RmaXggPDwgc3RhY2sucG9wCiAgICAgICAgZW5kCiAgICAgICAgc3RhY2sucG9wCiAgICAgICAgYnJlYWsKICAgICAgZW5kCiAgICAgIGlmICFzdGFjay5lbXB0eT8KICAgICAgICB3aGlsZSBvcGVyYXRvcltzdGFja1stMV1dID49IG9wZXJhdG9yW2V4cF0KICAgICAgICAgIHBvc3RmaXggPDwgc3RhY2sucG9wCiAgICAgICAgICBpZiBzdGFjay5lbXB0eT8KICAgICAgICAgICAgYnJlYWsKICAgICAgICAgIGVuZAogICAgICAgIGVuZAogICAgICBlbmQKICAgICAgYnJlYWsKICAgIGVuZAogICAgaWYgZXhwICE9ICcoJyAmJiBleHAgIT0gJyknCiAgICAgIHN0YWNrIDw8IGV4cAogICAgZW5kCiAgZW5kCmVuZAoKd2hpbGUgIXN0YWNrLmVtcHR5PwogIHBvc3RmaXggPDwgc3RhY2sucG9wCmVuZAoKcG9zdGZpeC5lYWNoIGRvIHxleHB8CiAgcHJpbnQgIiN7ZXhwfSAiCmVuZApwcmludCAiXG4iCg==