Stack Applications: Expression Conversion And Evaluation
Stacks are very useful in expressions like:
They help with:
- expression conversion
- expression evaluation
- matching brackets
- recursion and function calls
Types Of Expressions
Infix
Operator is between operands.
Prefix
Operator comes before operands.
Postfix
Operator comes after operands.
Why Prefix And Postfix Are Helpful
They avoid confusion about brackets and operator priority.
For example:
In postfix:
Now the order is clear.
Infix To Postfix
Main Idea
- Read expression left to right
- Send operands directly to output
- Put operators on stack
- Pop higher-priority operators before pushing lower-priority ones
- Pop all remaining operators at the end
Algorithm
Complexity
Time: O(n)
Why:
- each symbol is pushed or popped at most once
Space: O(n)
Infix To Prefix
One common method:
- reverse infix expression
- swap
(and) - convert to postfix
- reverse result
Complexity
Time: O(n)
Space: O(n)
Postfix Evaluation
Main Idea
- Read from left to right
- If operand, push it
- If operator, pop two operands
- apply operation
- push result back
Algorithm
Example
Process:
Answer: 14
Complexity
Time: O(n)
Space: O(n)
Prefix Evaluation
Main Idea
Read from right to left.
If operand, push it.
If operator, pop two values, apply operator, push result.
Algorithm
Complexity
Time: O(n)
Space: O(n)
Other Applications Of Stacks
- function call management
- undo and redo
- browser backtracking
- depth-first search
- balancing parentheses
Quick Summary
| Task | Time | Space |
|---|---|---|
| Infix to Postfix | O(n) |
O(n) |
| Infix to Prefix | O(n) |
O(n) |
| Postfix Evaluation | O(n) |
O(n) |
| Prefix Evaluation | O(n) |
O(n) |