Skip to content

Instantly share code, notes, and snippets.

@kkdai
Created February 5, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkdai/8822602 to your computer and use it in GitHub Desktop.
Save kkdai/8822602 to your computer and use it in GitHub Desktop.
#Ruby
def to_post_pre_fix(infix, isPost = true)
op_stack = [] #宣告成stack
return_str = "" #宣告成string
index_i=0
while (index_i < infix.size)
if (infix[index_i] == ")")
return_str << op_stack.pop #string operator add to back
elsif ("+-*/".include? infix[index_i])
isPost ? op_stack.push(infix[index_i]) : return_str << infix[index_i]
elsif (infix[index_i] == "(")
#do nothing
else
isPost ? return_str << infix[index_i] : op_stack.push(infix[index_i])
end
index_i += 1
end
return return_str
end
infix = "((a+(b*d))+(c/d))"
puts infix.inspect
puts "postfix =>" + to_post_pre_fix(infix)
puts "prefix =>" + to_post_pre_fix(infix, false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment