Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3
Algorithm to convert Infix to Reverse Polish Notation of expression
To convert infix expression to postfix expression Stack is used to store operators.
Input : String of Infix Expression
Store : Stack stores the Operator (Operator Stack) Output : String of Postfix Expression
Precedence of Operators High **(exponent) *, /, % Low +, -
The following algorithm converts infix to postfix (Reverse Polish) Expression
1. Push “(“ onto the stack and add “)” to the end of Input Expression P. 2. Scan input string from left to right character by character and repeat the following steps until STACK is empty. 3. If the character encountered is an operand then add it to output string P. 4. If the character encountered is left parenthesis '(', push it onto operator's STACK 5. If the character encountered is an operator X, then perform the following. a. If the precedence of scanned operator is greater than the top most operator of operator's STACK, send the scanned operator into output String. b. If the precedence of scanned operator is less than or equal to the top most operator of operator's STACK, Repeatedly pop the operators from operand's STACK until a low precedence operator than the scanned character is found. Never pop out '(' or ')' whatever may be the precedence level of scanned character. 6. If the character is right parenthesis ')' then a. Repeatedly pop out operators from operator's STACK and add to onto Output String P until left parenthesis is encountered. '('. b. Pop the left parenthesis “(“. 7. Output String P contains Reverse Polish Notation Evaluation of Reverse Polish Expression To evaluate postfix expression Operand Stack is used to store operand.
Input : Numerical Expression P in Reverse Polish Notation .
Store : Stack stores the Operand (Operand Stack) Output : Evaluated numerical value
1. Create a STACK to store operands (or values).
2. Add a right parenthesis “)” at the end of P. [This acts as a sentinel] 3. Scan P from left to right and repeat steps 4 and 5 for each element of P until the sentinel “)” is encountered 4. If the element is an operand (number), push it onto the STACK. 5. If the element is an operator X, then a. Pop two operands say A, B (first popped is A, Second popped element is B) from the STACK. b. Evaluate the Expression B X A. c. Push the result back onto the STACK. 6. Pop the value from the STACK. Popped value is the Result of expression.