Skip to main content

Posts

Showing posts with the label postfix expression evaluator

Postfix evaluator [EASY]

Question: Given a postfix expression, the task is to evaluate the expression and print the final value. Input: The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an postfix expression. Output: For each test case, evaluate the postfix expression and print the value. Constraints: 1 <= T <= 100 1 <= length of expression <= 100 Example: Input: 2 231*+9- 123+*8- Output: -4 -3 Algorithm: 1) Create a stack to store operands (or values). 2) Scan the given expression and do following for every scanned element. …..a) If the element is a number, push it into the stack …..b) If the element is a operator, pop operands for the operator from stack. Evaluate the operator and push the result back to the stack 3) When the expression is ended, the number in the stack is the final answer Example: Let the given expression be “2 10   + 96 -/“. We scan all elements one by one. 1) Scan ‘...