Stack Use-cases
- Post-fix expression evaluation
- Pre-fix expression evaluation
Post-fix expression evaluation
- Traverse the given expression left to right
- if number/operand encountered –>push to stack
- if operator (+ – * /) encounter –> pop top 2 operand and perform operation –>push the result back to stack
- repeat steps 2,3 till single operand remains as result
Example :
Input: str = “100 200 + 2 / 5 * 7 +”
Output: 757
Steps explained with diagram:
Pre-fix expression evaluation
- Traverse the given expression right to left
- if number/operand encountered –>push to stack
- if operator (+ – * /) encounter –> pop top 2 operand and perform operation –>push the result back to stack
- repeat steps 2,3 till single operand remains as result
Example :
Input : -+8/632
Output : 8
Input : -+7*45+20
Output : 25
Steps explained with diagram:
https://www.geeksforgeeks.org/evaluation-prefix-expressions/