Precedence Table
Symbol |
Input precedence function F |
Stack precedence function G |
Rank function R |
+, - |
1 |
2 |
-1 |
*, / |
3 |
4 |
-1 |
^ |
6 |
5 |
-1 |
Variables |
7 |
8 |
1 |
( |
9 |
0 |
- |
) |
0 |
- |
- |
Algorithm : REVPOL
- Given an input string INFIX containing an infix expression which has been padded on the right with ‘)’ and whose symbol have precedence value given by above table.
- A vector S used as a stack and a NEXTCHAR which when invoked returns the next character of its argument.
- This algorithm converts INFIX into reverse polish and places the result in the string POLISH.
- The integer variable TOP denotes the top of the stack. Algorithm PUSH and POP are used for stack manipulation.
- The integer variable RANK accumulates the rank of expression. Finally the string variable TEMP is used for temporary storage purpose.
- [Initialize stack]
TOP <-- 1
S[TOP] <-- ‘(‘
- [Initialize output string and rank count]
POLISH <-- ‘ ‘
RANK <-- 0
- [Get first input symbol]
NEXT<--NEXTCHAR(INFIX)
- [Translate the infix expression]
Repeat thru step 7 while NEXT != ‘ ‘
- [Remove symbols with greater precedence from stack]
IF TOP < 1
Then write (‘INVALID’)
EXIT
Repeat while G (S[TOP]) > F(NEXT)
TEMP <-- POP (S, TOP)
POLISH <-- POLISH O TEMP
RANK <-- RANK + R(TEMP)
IF RANK < 1
Then write (‘INVALID’)
EXIT
- [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
- [Get next symbol]
NEXT <-- NEXTCHAR(INFIX)
- [Is the expression valid]
IF TOP != 0 OR RANK != 1
Then write (‘INVALID ‘)
Else write (‘VALID ’)
Stack content for Infix to Postfix of expression A+B*C/D$E-(F*G)
Input Symbol |
Stack |
Postfix Expression |
Rank |
|
( |
|
0 |
A |
(A |
|
0 |
+ |
(+ |
A |
1 |
B |
(+B |
A |
1 |
* |
(+* |
AB |
2 |
C |
(+*C |
AB |
2 |
/ |
(+/ |
ABC* |
2 |
D |
(+/D |
ABC* |
2 |
$ |
(+/$ |
ABC*D |
3 |
E |
(+/$E |
ABC*D |
3 |
- |
(- |
ABC*DE$/+ |
1 |
( |
(-( |
ABC*DE$/+ |
1 |
F |
(-(F |
ABC*DE$/+ |
1 |
* |
(-(* |
ABC*DE$/+F |
2 |
G |
(-(*G |
ABC*DE$/+F |
2 |
) |
(- |
ABC*DE$/+FG* |
2 |
) |
|
ABC*DE$/+FG*- |
1 |
Postfix expression of given infix expression A+B*C/D$E-(F*G) is ABC*DE$/+FG*-