Loading lessons...
Stacks, Stack ADT & Expression Conversion
Stacks, Stack ADT & Expression Conversion
A Stack is a linear LIFO (Last-In, First-Out) ADT where insertions (Push), deletions (Pop), and inspection (Peek/Peep) all occur at one end called TOP.
Stack & Infix-to-Postfix Conversion
1. Array vs Linked Stack Implementations
- Array Stack: Uses
int stack[MAX]andint top = -1. - Overflow:
top == MAX - 1| Underflow:top == -1. Push(x),Pop(),Peek()all run in O(1).
void push(int st[], int *top, int max, int val) {
if (*top == max - 1) { printf("Stack Overflow\n"); return; }
st[++(*top)] = val;
}
int pop(int st[], int *top) {
if (*top == -1) { printf("Stack Underflow\n"); return -1; }
return st[(*top)--];
}- Linked Stack: Inserts and deletes at the head (
TOP) of a Singly Linked List, drawing nodes fromAVAIL/ heap-grows dynamically without a fixedMAX.
2. Classic Applications of Stacks
- System Call Stack: Stores activation records (return addresses, arguments, local variables).
- Base Conversion / Data Reversal: E.g., Decimal
233→ Binary11101001by pushingn % 2and popping in reverse. - Delimiter / Parentheses Matching: Push opening brackets
(,{,[; on closing bracket, pop and verify match. - Undo/Redo & Browser Back Stack.
3. Infix, Prefix & Postfix Expressions
- Infix:
A + B(ambiguous without precedence & parentheses). - Prefix (Polish):
+ A B(operator precedes operands; no parentheses needed). - Postfix (Reverse Polish):
A B +(operator follows operands; evaluated left-to-right in a single pass!).
Operator Precedence & Associativity
- Highest:
^(Right-to-Left associative) - Middle:
*,/,%(Left-to-Right associative) - Lowest:
+,-(Left-to-Right associative)
Infix → Postfix Algorithm (prcd(op1, op2))
- Operand → append directly to output.
(→ push onto stack.)→ pop and append until(is popped (discard both).- Operator
op: while stack top has higher (or equal, if left-associative) precedence, pop and append; then pushop. - End of expression → pop remaining operators.
Worked Conversion: ((A - (B + C)) * D) ^ (E + F) → ABC+-D*EF+^
Infix → Prefix Trick: Reverse the infix string (swapping ( and )), convert to postfix (popping only on strictly higher precedence), then reverse the result! E.g., (A + B) * C → * + A B C.
Postfix Evaluation Worked Trace
Evaluate 6 2 3 + - 3 8 2 / + * 2 ^ 3 + left-to-right:
- Push
6, 2, 3→+pops2, 3, pushes5 -pops6, 5, pushes1- Push
3, 8, 2→/pops8, 2, pushes4→+pops3, 4, pushes7 *pops1, 7, pushes7- Push
2→^pops7, 2, pushes49 - Push
3→+pops49, 3, pushes52!
Stack Algorithms (Array and Linked)
PUSH(STACK, TOP, MAXSTK, ITEM) - array
- If TOP = MAXSTK, write OVERFLOW and Exit.
- Set TOP := TOP + 1.
- Set STACK[TOP] := ITEM.
- Exit.
POP(STACK, TOP, ITEM) - array
- If TOP = 0 (or −1 for 0-based), write UNDERFLOW and Exit.
- Set ITEM := STACK[TOP].
- Set TOP := TOP − 1.
- Exit.
PEEP / PEEK - return STACK[TOP] without changing TOP (UNDERFLOW if empty). The generalized PEEP(i) returns STACK[TOP − i + 1], the i-th element from the top.
PUSH (linked) - get NEW from AVAIL (OVERFLOW if AVAIL = NULL); INFO[NEW] := ITEM; LINK[NEW] := TOP; TOP := NEW.
POP (linked) - if TOP = NULL, UNDERFLOW; ITEM := INFO[TOP]; TEMP := TOP; TOP := LINK[TOP]; return TEMP to AVAIL.
Four Categories of Stack Applications
| Category | Idea | Example |
|---|---|---|
| Reversing data | Push everything, then pop: the order is reversed | Reverse a string; decimal to binary conversion |
| Parsing | Break data into parts and check structure | Balanced-parentheses checking, compilers |
| Postponing | Delay using data until later | Infix → postfix conversion, postfix evaluation |
| Backtracking | Remember choices to go back to | Maze solving, 8-Queens, DFS |
Example-Decimal 233 to binary
Divide by 2 and push each remainder, then pop:
| 233 ÷ 2 | 116 ÷ 2 | 58 ÷ 2 | 29 ÷ 2 | 14 ÷ 2 | 7 ÷ 2 | 3 ÷ 2 | 1 ÷ 2 |
|---|---|---|---|---|---|---|---|
| r 1 | r 0 | r 0 | r 1 | r 0 | r 1 | r 1 | r 1 |
Popping gives 11101001 = 128 + 64 + 32 + 8 + 1 = 233 ✓.
Example-Parentheses checking
Scan left to right: push every (, pop on every ).
((A+B)*C)→ every)finds a(, stack empty at the end → balanced.((A+B)*C→ stack still holds one(at the end → unbalanced (missing)).(A+B))→ a)arrives with the stack empty → unbalanced (extra)).
Manual Conversion by Full Parenthesisation
- Fully parenthesise the expression according to precedence and associativity.
- Move each operator to replace its closing bracket (postfix) or its opening bracket (prefix).
- Remove all brackets.
Example: (A + B) × C + D + E × F − G
- Fully parenthesised: ((((A + B) × C) + D) + (E × F)) − G
- Postfix: A B + C × D + E F × + G −
- Prefix: − + + × + A B C D × E F G
The precedence function prcd(op1, op2) returns TRUE when op1 (on the stack) should be popped before op2 (incoming):
- prcd(
*,+) = TRUE, prcd(+,+) = TRUE (left associative), prcd(+,*) = FALSE. - prcd(
$,$) = FALSE (exponent is right associative). - prcd(
(, op) = FALSE for any op; prcd(op,() = FALSE; prcd(op,)) = TRUE for any op other than(.
Stack trace: A + B × C − D / E
| Symbol | Stack | Postfix so far |
|---|---|---|
| A | A | |
| + | + | A |
| B | + | A B |
| × | + × | A B |
| C | + × | A B C |
| − | − | A B C × + |
| D | − | A B C × + D |
| / | − / | A B C × + D |
| E | − / | A B C × + D E |
| end | A B C × + D E / − |
When − arrives, * and + both have precedence ≥ −, so both are popped before − is pushed.
Prefix of a larger expression
For ((A − (B + C)) × D) ↑ (E + F) the prefix form is ↑ × − A + B C D + E F (the outermost operator ↑ comes first).
When evaluating a postfix expression, the operand stack never needs to hold more than (number of operands − number of operators already applied) values; for a valid expression with n operands it holds at most n.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. Write the algorithm to convert an Infix expression to Postfix using a Stack. Convert
((A - (B + C)) * D) ^ (E + F)step-by-step. (7.5 Marks) - Write: Precedence/associativity rules (
^right-to-left,*/left-to-right), the 5-step stack algorithm, and the full 3-column trace table (Token | Stack | Output→ABC+-D*EF+^). - Q2. Evaluate the Postfix expression
6 2 3 + - 3 8 2 / + * 2 ^ 3 +using a Stack. (5 Marks) - Write: Step-by-step operand stack trace showing every push, pop, and intermediate result arriving at
52.