I am looking for algorithm postfix to infix notation which will produce the minimum number of the parentheses.
I have found that but it will produce many, many parentheses: http://tajendrasengar.blogspot.com/2011/09/postfix-to-infix-algorithm.html
For example
The input:
<ONP>abcd*/+~
The result:
<INF>~(a+b/(c*d))
What you need to do if you really want as few parentheses as possible, is similar to what the algorithm you linked to says. However...
Stack
. Namely, the last operator used in the operand. You could use a second Stack
for this. If the operand is not composite, you could add null
to the second Stack
, since there is no operator.String
with parentheses. That is done elsewhere in the algorithm (see below).When you pop the top two values from each of the Stack
s, you have 3 operators at hand:
Depending on these three operators, you should encapsulate the first and/or second operand with parentheses, before combining them.
You could use operator precedence to determine whether there should be parentheses. The order goes like this: (none), {"*", "/"}, {"+", "-"}
"/"
or "-"
.The rest should be done the way your algorithm described.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With