Lesson 7 +35 XP

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 ConversionStack & Infix-to-Postfix Conversion

1. Array vs Linked Stack Implementations

  • Array Stack: Uses int stack[MAX] and int top = -1.
  • Overflow: top == MAX - 1 | Underflow: top == -1.
  • Push(x), Pop(), Peek() all run in O(1).
C
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 from AVAIL / heap-grows dynamically without a fixed MAX.

2. Classic Applications of Stacks

  1. System Call Stack: Stores activation records (return addresses, arguments, local variables).
  2. Base Conversion / Data Reversal: E.g., Decimal 233 → Binary 11101001 by pushing n % 2 and popping in reverse.
  3. Delimiter / Parentheses Matching: Push opening brackets (, {, [; on closing bracket, pop and verify match.
  4. 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))

  1. Operand → append directly to output.
  2. ( → push onto stack.
  3. ) → pop and append until ( is popped (discard both).
  4. Operator op: while stack top has higher (or equal, if left-associative) precedence, pop and append; then push op.
  5. 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:

  1. Push 6, 2, 3 → + pops 2, 3, pushes 5
  2. - pops 6, 5, pushes 1
  3. Push 3, 8, 2 → / pops 8, 2, pushes 4 → + pops 3, 4, pushes 7
  4. * pops 1, 7, pushes 7
  5. Push 2 → ^ pops 7, 2, pushes 49
  6. Push 3 → + pops 49, 3, pushes 52!

Stack Algorithms (Array and Linked)

PUSH(STACK, TOP, MAXSTK, ITEM) - array

  1. If TOP = MAXSTK, write OVERFLOW and Exit.
  2. Set TOP := TOP + 1.
  3. Set STACK[TOP] := ITEM.
  4. Exit.

POP(STACK, TOP, ITEM) - array

  1. If TOP = 0 (or −1 for 0-based), write UNDERFLOW and Exit.
  2. Set ITEM := STACK[TOP].
  3. Set TOP := TOP − 1.
  4. 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

CategoryIdeaExample
Reversing dataPush everything, then pop: the order is reversedReverse a string; decimal to binary conversion
ParsingBreak data into parts and check structureBalanced-parentheses checking, compilers
PostponingDelay using data until laterInfix → postfix conversion, postfix evaluation
BacktrackingRemember choices to go back toMaze solving, 8-Queens, DFS

Example-Decimal 233 to binary

Divide by 2 and push each remainder, then pop:

233 ÷ 2116 ÷ 258 ÷ 229 ÷ 214 ÷ 27 ÷ 23 ÷ 21 ÷ 2
r 1r 0r 0r 1r 0r 1r 1r 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

  1. Fully parenthesise the expression according to precedence and associativity.
  2. Move each operator to replace its closing bracket (postfix) or its opening bracket (prefix).
  3. 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

SymbolStackPostfix so far
AA
++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
endA 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).

ℹ️ Note

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.

🎯 END-TERM EXAM PREP

📝 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.