1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 2

CAP7004 · Unit 2: Linear data structures

Stacks and their applications

8 practice questions

Key points

  • LIFO; push, pop, peek are O(1)
  • Call stack, undo, bracket matching, expression evaluation
  • Postfix: pop right operand first
  • Underflow = pop empty, overflow = push full

A stack is a Last-In-First-Out (LIFO) structure. Main operations: push (add on top), pop (remove top), peek (read top), is_empty. In Python a list works: append pushes and pop() pops, both O(1).

Applications:

  • Function calls: the call stack stores return addresses and local variables.
  • Undo in editors and browser back history.
  • Balanced brackets: push openers; on a closer, pop and compare. The string is balanced only if all pairs match and the stack ends empty. {[()]} is balanced; ([)], (( and ()) are not.
  • Postfix evaluation: scan tokens; push operands; for an operator pop b then a, push a op b. Example 2 3 4 * + gives 2 + 3*4 = 14.
  • Infix to postfix: output operands; keep operators on a stack by precedence (* / above + -). a+b*c becomes abc*+; (a+b)*c becomes ab+c*.

Overflow happens when pushing to a full fixed-size stack; underflow when popping an empty one.

Exam pitfall: in postfix, the first popped value is the right operand, so 6 2 - is 6 - 2 = 4, not 2 - 6.

Try two questions

Question 1 · Tier 2, Understand

After push(1), push(2), push(3), pop(), the top of the stack is:

  1. 3
  2. 1
  3. 2
  4. Empty
Show the answer

C. 3 was removed, leaving 2 on top.

Question 2 · Tier 2, Understand

The value of the postfix expression 2 3 4 * + is:

  1. 20
  2. 24
  3. 9
  4. 14
Show the answer

D. 3*4 = 12, then 2 + 12 = 14.