Problem Statement - Given a string of postfix expression, You have to evaluate value of given postfix expression.
Solution - First we will understand it by an example.
We are taking an postfix expression 5462-*+ mentioned in above section for our understanding. Below is the steps how an post fix expression is evaluated.
1. First we scan the string left to right till first encounter of an operation symbol. In our case it is "-" symbol.
2. Based on nature of operation like unary, binary etc., we go back and select same number of operands(In case of unary select one operand, In case of binary 2 operands ).
3. Process that part of expression like operand1 operation operand2
In our example "-" is the first occurance of operation and it is a binary operation nd its 2 previous operands are 2 and 6. so part 62- will be processed first(6-2) and result will be stored at same place as below.
Next * is the binary operation and 2 operands are 4,4 so it will be processed as below:Selection of Data Structure:In above example we every time we are depending upon operands which are last appearing in string sequence. And operation of the result performed on operand are stored at last position. If we try to remember such data structure where operation is performed on last inserted symbol then it is Stack data structure. We can solve this problem with the stack as given below:
Above image shows the processing of input postfix expression, which is described below:
- In Fig 1 input string is scanned from left to right. During scanning all operands are pushed onto the stack.
- In process of the scanning of string symbols once we encounter any operation symbol based of the nature of operation (like unary or binary etc.) required number of operands from stack is popped and operation is performed on popped operands. Result of operation is again pushed back to operand stack.
- In our example in Fir 2 first we encounter symbol "-" which is binary operator. Accordingly we pop two operands 2 and 6 where operand1=6 and operand2=2. so result=6-2=4. Here 4 again pushed back to the operand stack.
- Same as step 2 and 3, next symbol in input string "*" is processed in Fig 3 and "+" symbol is processed in Fig 4. And finally result 21 is achieved.
2. For i=1 to length(inpurStr)
3. char ch=inpurStr[i]
4. if(isNumber(ch))
5. S.push(ch)
6. else
7. operator=ch
8. operand2=S.pop()
9. operand1=S.pop()
10. tempResult=operand1 operator operator2
11. S.push(tempResult)
12. return S.pop()