📖 Scenario: You are building a simple calculator that reads a postfix expression and calculates the result. Postfix expressions have operators after their operands, like 23+ which means 2 + 3.This calculator uses a stack to keep track of numbers and applies operators step-by-step.
🎯 Goal: Build a Rust program that uses a stack to evaluate a postfix expression and prints the final result.
📋 What You'll Learn
Create a vector of characters representing the postfix expression
Create a stack using a vector to hold integer values
Loop through each character in the postfix expression
Push numbers onto the stack
Pop two numbers from the stack when an operator is found and apply the operator
Push the result back onto the stack
Print the final result from the stack
💡 Why This Matters
🌍 Real World
Postfix expressions are used in calculators and compilers to evaluate mathematical expressions efficiently without parentheses.
💼 Career
Understanding stack-based expression evaluation is important for software developers working on interpreters, compilers, and calculators.
Progress0 / 4 steps
1
Create the postfix expression vector
Create a vector called postfix_expr with these exact characters: '2', '3', '1', '*', '+', '9', '-'
DSA Rust
Hint
Use vec![] to create a vector of characters.
2
Create an empty stack vector for integers
Add a mutable vector called stack of type Vec initialized as empty after the postfix_expr declaration
DSA Rust
Hint
Use let mut stack: Vec = Vec::new(); to create an empty stack.
3
Loop through the postfix expression and evaluate
Add a for loop with variable ch iterating over postfix_expr. Inside the loop, if ch is a digit, convert it to i32 and push it to stack. If ch is an operator '+', '-', or '*', pop two values from stack, apply the operator, and push the result back to stack. Use stack.pop().unwrap() to pop values safely.
DSA Rust
Hint
Use ch.is_digit(10) to check if character is a digit. Use match to apply operators.
4
Print the final result from the stack
Add a println! statement to print the last value in stack using stack.pop().unwrap() after the loop ends
DSA Rust
Hint
The final result of the postfix expression is printed as an integer.
Practice
(1/5)
1. What is the main data structure used to evaluate a postfix expression?
easy
A. Queue
B. Stack
C. Array
D. Linked List
Solution
Step 1: Understand postfix evaluation method
Postfix expressions are evaluated using a stack because operands are pushed and operators pop operands to compute results.
Step 2: Identify the correct data structure
Stack allows last-in, first-out operations needed for postfix evaluation.
2. Which Rust code snippet correctly pushes an integer onto a stack represented by a vector named stack?
easy
A. stack.append(5);
B. stack.add(5);
C. stack.push(5);
D. stack.insert(5);
Solution
Step 1: Recall Rust vector push method
Rust vectors use push to add elements at the end.
Step 2: Match correct method to push integer
stack.push(5); correctly adds 5 to the vector stack.
Final Answer:
stack.push(5); -> Option C
Quick Check:
Use push() to add element to vector [OK]
Hint: Use push() to add elements to Rust vectors [OK]
Common Mistakes:
Using add() which doesn't exist
Using insert() without index
Using append() incorrectly
3. What is the output of the following Rust code that evaluates the postfix expression "23+5*"?
fn evaluate_postfix(expr: &str) -> i32 {
let mut stack = Vec::new();
for ch in expr.chars() {
if ch.is_digit(10) {
stack.push(ch.to_digit(10).unwrap() as i32);
} else {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
let res = match ch {
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => a / b,
_ => 0,
};
stack.push(res);
}
}
stack.pop().unwrap()
}
fn main() {
println!("{}", evaluate_postfix("23+5*"));
}
Push 2, push 3, '+' pops 3 and 2, adds to 5, push 5, push 5, '*' pops 5 and 5, multiplies to 25.
Step 2: Final stack value after evaluation
Stack ends with single value 25, which is printed.
Final Answer:
25 -> Option A
Quick Check:
2+3=5; 5*5=25 [OK]
Hint: Calculate stepwise: operands push, operators pop and compute [OK]
Common Mistakes:
Mixing operand order
Not popping two operands
Confusing operator precedence
4. Identify the error in the following Rust code snippet that evaluates a postfix expression:
fn evaluate_postfix(expr: &str) -> i32 {
let mut stack = Vec::new();
for ch in expr.chars() {
if ch.is_digit(10) {
stack.push(ch.to_digit(10).unwrap() as i32);
} else {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
let res = match ch {
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => a / b,
_ => 0,
};
stack.push(res);
}
}
stack.pop().unwrap()
}
medium
A. Stack is not initialized
B. Using unwrap() causes panic
C. Missing handling for invalid characters
D. Operands are popped in wrong order (a and b swapped)
Solution
Step 1: Check operand popping order
Operands must be popped as b then a to maintain correct order for operations like subtraction and division.
Step 2: Identify the swap error
Code pops a first then b, which reverses operand order and causes wrong results.
Final Answer:
Operands are popped in wrong order (a and b swapped) -> Option D
Quick Check:
Pop b then a for correct operand order [OK]
Hint: Pop second operand first, then first operand [OK]
Common Mistakes:
Swapping operand order
Ignoring unwrap panic possibility
Not validating input characters
5. Given the postfix expression "82/3-4*", what is the correct evaluation result using a stack-based approach in Rust?