How to evaluate a postfix expression with a stack
Postfix evaluation requires a single left-to-right pass using a Last-In-First-Out (LIFO) stack. It applies to expressions in Reverse Polish Notation (RPN) where operators strictly follow their operands.
The setup
Initialize an empty stack capable of holding numeric values. Ensure the input postfix expression is properly tokenized into distinct operands (numbers) and operators.
The steps
- Read the expression from left to right, one token at a time. 2. If the token is a number, push it onto the stack. 3. If the token is an operator, pop the top two numbers from the stack. 4. Apply the operator to these two numbers. The first number popped is the right operand, and the second number popped is the left operand. 5. Push the resulting value back onto the stack. 6. Repeat until all tokens are processed. 7. The final result is the single remaining value on the stack.
Checking the result
Verify that exactly one element remains on the stack after all tokens are processed. If the stack is empty or contains multiple elements at the end, the original expression was malformed.
Common errors
A frequent error is reversing the operand order during subtraction or division. Remember that for an expression like , is popped first and is popped second. The operation must be evaluated as .
Worked example
Evaluate the postfix expression:
Token 5: push 5. Stack: [5]. Token 1: push 1. Stack: [5, 1]. Token 2: push 2. Stack: [5, 1, 2]. Token +: pop 2, pop 1, compute 1 + 2 = 3, push 3. Stack: [5, 3]. Token 4: push 4. Stack: [5, 3, 4]. Token *: pop 4, pop 3, compute 3 * 4 = 12, push 12. Stack: [5, 12]. Token +: pop 12, pop 5, compute 5 + 12 = 17, push 17. Stack: [17]. Token 3: push 3. Stack: [17, 3]. Token -: pop 3, pop 17, compute 17 - 3 = 14, push 14. Stack: [14]. Final result: 14.
FAQ
Run your own problem
References: Introduction to Algorithms, Third Edition (Cormen, Leiserson, Rivest, Stein) · Data Structures and Algorithm Analysis in C++ (Mark Allen Weiss)
See also