Stack applications: recursion and expression conversion
Stack operations and the call stack let engineers implement recursion and convert/evaluate expressions (infix, postfix, prefix) efficiently using LIFO discipline.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Stacks and recursion are used everywhere in software engineering: the programming language runtime uses a call stack to manage function calls and local variables; compilers and interpreters use stacks to convert and evaluate expressions and to parse source code; algorithmic problems (backtracking, DFS) use stacks explicitly or implicitly. Knowing stack-based expression conversion and how recursion maps to stack frames helps you write correct parsers, evaluate calculators, and reason about recursion depth and stack overflow.
Key ideas
Recursion: A function is recursive if it calls itself directly or indirectly. Each active call creates an activation record (stack frame) containing return address, parameters, local variables, and saved registers. The sequence of activation records is stored on the call stack following LIFO order. Recursion depth equals the maximum number of simultaneously active calls.
Call stack diagram to draw for a recursive program (label exactly): draw a vertical stack; at bottom label "main" frame; above it, successive frames labelled with function name and parameter values, local variables, and return address; mark top as current call. Also draw arrow showing flow when a function returns (pop). For tail recursion, indicate that some compilers can optimize and reuse the frame (tail-call optimization) — mention only if the language/runtime supports it.
Stack invariant while converting expressions: when parsing left to right, the operators on the stack are those whose application is still pending; operands are directly appended to output. The invariant ensures final output has operands in the order required by postfix/prefix semantics.
Expression forms
- Infix: operator between operands, e.g., a + b. Common for humans.
- Postfix (Reverse Polish Notation): operator after operands, e.g., a b +. Easy to evaluate with a stack.
- Prefix (Polish Notation): operator before operands, e.g., + a b. Also easy to evaluate with a stack.
Operator precedence and associativity: precedence is a ranking that determines order of operations when parentheses are absent (higher precedence binds tighter). Associativity decides order when precedence ties (left-associative means evaluate left-to-right; right-associative means right-to-left). Typical operator set used in algorithms: '^' has highest precedence and is right-associative; '*' and '/' next (left-associative); '+' and '-' lowest (left-associative). Parentheses '(' and ')' override precedence.
Infix to Postfix conversion algorithm (shunting-yard style) — exact step-by-step method
- Create an empty operator stack S and an empty output list O.
- Read tokens from left to right.
- If token is an operand, append it to O.
- If token is an operator op1: a. While S is not empty and top of S is an operator op2 and ((op1 is left-associative and precedence(op1) <= precedence(op2)) or (op1 is right-associative and precedence(op1) < precedence(op2))) then pop op2 from S and append op2 to O. b. Push op1 onto S.
- If token is '(', push it onto S.
- If token is ')', pop operators from S and append to O until '(' is at top; pop the '('. If no '(' is found, the expression is invalid.
- After input consumed, pop and append all remaining operators from S. If any parentheses remain, the expression is invalid.
Assumptions: tokens are well-formed (operands, operators, parentheses); precedence and associativity are known; unary operators require special handling (not covered here unless explicitly implemented).
Correctness idea: the algorithm maintains that any operator on the stack has not yet found all operands that should appear before it in postfix form. When a lower-precedence operator arrives, higher-precedence operators are popped first, which ensures correct ordering.
Postfix evaluation algorithm
- Create an empty stack S.
- Read tokens left to right.
- If token is an operand (number), push it onto S.
- If token is an operator, pop required number of operands from S (for binary operator pop right operand then left operand), compute result = left op right, push result back on S.
- After all tokens, the stack should contain exactly one value: the final result. If stack has >1 or <1 elements at the end, the expression was invalid.
Complexity: both conversion and evaluation run in O(n) time for n tokens and O(n) extra space for the stack. To obtain prefix from infix, either use a mirrored shunting-yard that scans right-to-left (handling associativity accordingly), or more simply: reverse the infix string, swap '(' with ')', run infix-to-postfix, then reverse the result to get prefix; to evaluate a prefix expression, scan tokens right-to-left, pushing operands and applying operators to the two most recent operands.
Relationship between recursion and explicit stack: any recursive function can be converted to an iterative one using an explicit stack of activation-record-like objects; likewise, many stack-based algorithms simulate recursion explicitly.
Formulas
stack<T> s; — declare a stack of type T in C++ (std::stack from <stack> or <bits/stdc++.h>).
s.push(x); — push x onto stack s; x has type T.
s.pop(); — remove the top element from s (no return); call s.top() before pop to read it.
s.top(); — returns reference to top element of s.
s.empty(); — returns true if s has no elements.
precedence(op) — a mapping from operator to integer. Example when used in algorithm: precedence('^') = 3, precedence('*') = 2, precedence('/') = 2, precedence('+') = 1, precedence('-') = 1.
time(infix_to_postfix) = O(n) — n is number of tokens (operands + operators + parentheses).
space(infix_to_postfix) = O(n) — extra space for operator stack and output.
Worked examples
Example 1 — C++ program: Infix to Postfix conversion (operands are single-letter or single-digit tokens, no unary operators). Program reads one line (an expression) and prints the postfix string. Assumes the input has balanced parentheses; this code does not report mismatches (an unmatched ')' is ignored, and any unmatched '(' will appear in the output).
#include <bits/stdc++.h>
using namespace std;
int prec(char op) {
if (op == '^') return 3;
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
bool isRightAssoc(char op) {
return op == '^';
}
int main() {
string s;
getline(cin, s); // read whole expression line
stack<char> st;
string out;
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
if (isspace(c)) continue;
if (isalnum(c)) {
out.push_back(c);
} else if (c == '(') {
st.push(c);
} else if (c == ')') {
while (!st.empty() && st.top() != '(') {
out.push_back(st.top()); st.pop();
}
if (!st.empty() && st.top() == '(') st.pop(); // remove '('
} else { // operator
while (!st.empty()) {
char top = st.top();
if (top == '(') break;
int p1 = prec(c), p2 = prec(top);
if ((!isRightAssoc(c) && p1 <= p2) || (isRightAssoc(c) && p1 < p2)) {
out.push_back(top); st.pop();
} else break;
}
st.push(c);
}
}
while (!st.empty()) { out.push_back(st.top()); st.pop(); }
cout << out << '\n';
return 0;
}
Sample input (single line):
(a+(b*c))-d
Exact output:
abc*+d-
Example 2 — C++ program: Evaluate a space-separated postfix expression with integer operands (multi-digit allowed). Program reads one line and prints the integer result. Operators supported: + - * / ^ (integer power). Division uses integer division like C++ '/'. Assumes exponent b >= 0 for '^' (negative exponents are not supported) and inputs never divide by zero.
#include <bits/stdc++.h>
using namespace std;
long long ipow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) res *= a;
a *= a; b >>= 1;
}
return res;
}
int main() {
string line;
getline(cin, line);
stringstream ss(line);
string token;
stack<long long> st;
while (ss >> token) {
if (isdigit(token[0]) || (token.size()>1 && token[0]=='-' && isdigit(token[1]))) {
st.push(stoll(token));
} else {
if (st.size() < 2) { cout << "ERROR\n"; return 0; }
long long b = st.top(); st.pop();
long long a = st.top(); st.pop();
if (token == "+") st.push(a + b);
else if (token == "-") st.push(a - b);
else if (token == "*") st.push(a * b);
else if (token == "/") st.push(a / b);
else if (token == "^") st.push(ipow(a,b));
else { cout << "ERROR\n"; return 0; }
}
}
if (st.size() != 1) { cout << "ERROR\n"; return 0; }
cout << st.top() << '\n';
return 0;
}
Sample input (single line):
10 2 3 * + 9 -
Exact output:
7
Worked example (theory) — Show call stack for recursion
Question: Draw the call stack for function f(n) that calls f(n-1) until n==0, with n initialised to 3. Describe what to draw and label.
Model answer: Draw a vertical stack. Bottom frame: label "main". Above it draw frame f(3): show parameter n = 3, local variables (if any), return address pointing to main after call. Above that f(2) with n = 2, above that f(1) with n = 1, above that f(0) with n = 0 (top). Mark top as currently executing. Then indicate that when f(0) returns, its frame is popped and control returns to f(1), then f(1) returns and so on.
Common mistakes
- Not handling parentheses correctly: failing to detect mismatched parentheses.
- In postfix evaluation, popping operands in the wrong order (popping left operand first) reverses operations for non-commutative operators.
- Assuming recursion uses less memory than iteration; recursion uses stack frames — deep recursion can cause stack overflow.
- In C++ programs, using s.pop() and then s.top() (order wrong) — s.pop() discards top value, so read top before pop.
For your exam
Typical question types
- Definitions: define stack, LIFO, activation record, precedence, associativity.
- Short notes: explain conversion algorithm, call stack, relation between recursion and stack.
- Derivations: step-by-step run of infix to postfix with the stack state table for each input token; draw stack snapshots and output string at each step.
- Programs: implement infix-to-postfix conversion or postfix evaluation in C/C++; include sample runs.
- Diagrams: draw call stack for given recursion depth and show activation records.
What a full-marks answer includes
- Precise definitions with bold terms as asked.
- For algorithms: pseudocode, explanation of precedence/associativity handling, stack invariant, correctness idea, and time/space complexity.
- For program questions: correct, compilable code; sample input and exact output; explanation of edge cases (parentheses, invalid expressions).
Quick check
- What stack operation reads the top element without removing it?
- In infix to postfix conversion, when an operator with lower precedence arrives, should higher-precedence operators on the stack be popped first? (yes/no)
- For the postfix tokens "5 6 7 * +", what is the evaluation result?
Answers: peek/top; yes; 47
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?