Write an algorithm for the evaluation of Postfix expression using stack.

Added 2 weeks ago
Active
Viewed 23
Ans

Input: A valid postfix expression

Output: The final result after evaluating the expression

Steps:

1. Create an empty stack to store operands.

2. Scan the postfix expression from left to right.

3. For each symbol in the expression:

 a. If the symbol is an operand, push it onto the stack.

 b. If the symbol is an operator (+, −, ×, ÷):

 - Pop the top two elements from the stack.

 - Apply the operator on them (second popped element ∘ first popped element).

  - Push the result back onto the stack.

4. After the entire expression is scanned, the final result will be on the top of the stack.

5. Pop and return this result.


Example:


Postfix Expression: 5 6 2 + *

• Push 5

• Push 6

• Push 2

• '+' → Pop 6 and 2 → 6 + 2 = 8 → Push 8

• '*' → Pop 5 and 8 → 5 * 8 = 40 → Push 40

• Final Result: 40



Related Questions