Follow Us
Select Medium / माध्यम चुनें:
Eng (English) Hindi (हिन्दी)
CBSE • Class XII • Computer Science • Ch 3
Estimated Time: 45 Mins
Study Progress: In Progress

Stack

In CBSE Class 12 Computer Science, "Stack" provides an authoritative, mathematically rigorous master study guide on Last-In-First-Out (LIFO) linear data structures. This comprehensive chapter covers the theoretical definition of Stacks, the top pointer abstraction, core primitive operations (`push`, `pop`, `peek`, `isEmpty`), error conditions (Stack Underflow vs Stack Overflow), complete list-based programmatic implementations in Python, and real-world computer science applications including function execution call stacks, parenthesis matching algorithms, infix to postfix expression conversions, and postfix evaluation matrices aligned with the 2026–27 CBSE curriculum.

How Does Your Browser Back Button, Text Editor Undo, and CPU Call Stack Keep Track of History?

When you browse ten different web pages and click the "Back" button, you don't return to the first website you visited an hour ago; you return to the very last page you just looked at. When you press Ctrl+Z in Microsoft Word or VS Code, it doesn't undo your first keystroke from this morning; it reverses the single most recent character you typed. At the physical hardware level, when a Python program calls function A(), which calls function B(), which calls C(), the computer must remember exactly where to return after each function finishes. How do software systems maintain history so that the last thing added is always the first thing removed? They use the most foundational linear data structure in computer science: the Stack.

Why This Chapter Matters

The Stack is not merely an abstract exam concept—it is the direct architectural engine behind modern computing. Operating system memory is split into Heap and Stack; every function invocation in Python, C++, or Java pushes an execution stack frame containing local variables and return pointers onto the hardware call stack. Stacks drive compiler syntax parsing, recursive algorithms, backtracking engines in maze-solvers, and depth-first search (DFS) graph traversals. Mastering stack implementations and boundary checks (Underflow/Overflow) is essential for any aspiring software engineer.

Before You Begin (Prerequisites)

  • Python lists, list indexing, and list operations (`append()`, `pop()`).
  • Functions, parameters, and return statements.
  • Logical conditions: testing whether a collection is empty.

What You Will Learn (Core Objectives)

  • Define a Linear Data Structure and explain the Last-In-First-Out (LIFO) / First-In-Last-Out (FILO) access discipline.
  • Implement the 4 core primitive Stack operations: `push(item)`, `pop()`, `peek()`, and `isEmpty()`.
  • Identify and prevent Stack Underflow (popping from an empty stack) and Stack Overflow (exceeding fixed bounds).
  • Construct production-grade Python functions implementing a stack using list append and pop methods.
  • Apply Stacks to solve classic computer science problems: Parenthesis balance validation and string reversal.
  • Trace and execute Infix, Prefix, and Postfix notation conversions and postfix arithmetic evaluation.

Chapter Roadmap & Progression

1 1. The LIFO Paradigm & Stack Abstra...
2 2. Complete List-Based Stack Implem...
3 3. Algorithmic Applications of Stac...

Complete Concept Guide (100% Curriculum Coverage)

1. The LIFO Paradigm & Stack Abstract Data Type (ADT)

Understand

A Stack is a linear data structure in which all element insertions and deletions are restricted to a single end, universally referred to as the TOP of the stack. It operates strictly under the LIFO (Last-In, First-Out) or FILO (First-In, Last-Out) access discipline.

Core Primitive Operations:
  • `push(item)`: Inserts a new element at the TOP of the stack. Increments stack size.
  • `pop()`: Removes and returns the element currently residing at the TOP of the stack. Decrements stack size. If the stack is empty, triggers Stack Underflow.
  • `peek()` / `top()`: Returns the value of the top element *without* removing it. Triggers Underflow if the stack is empty.
  • `isEmpty()`: Boolean predicate returning `True` if the stack contains zero elements, `False` otherwise.
Stack Boundary Conditions:
  • Stack Underflow: An error condition that occurs when an algorithm attempts to execute a `pop()` or `peek()` operation on a stack that contains no elements (`isEmpty() == True`).
  • Stack Overflow: An error condition that occurs in a bounded, fixed-capacity stack when a `push()` is attempted on an already full stack. (Note: Dynamic Python lists grow automatically, so overflow occurs only when physical system memory is exhausted or recursive recursion limits are exceeded).

2. Complete List-Based Stack Implementation in Python

Python Implementation

In Python, a stack is natively implemented using a standard dynamic list where the end of the list (`lst[-1]`) acts as the TOP of the stack because `append()` and `pop()` operate at the end in $O(1)$ constant amortized time:

# Production-Grade Stack Implementation:
def create_stack():
    return []

def isEmpty(stack):
    return len(stack) == 0

def push(stack, item):
    stack.append(item)
    print(f"Pushed: {item} | Current Stack: {stack}")

def pop(stack):
    if isEmpty(stack):
        print("Stack Underflow Error: Cannot pop from an empty stack!")
        return None
    removed_item = stack.pop()
    print(f"Popped: {removed_item} | Remaining Stack: {stack}")
    return removed_item

def peek(stack):
    if isEmpty(stack):
        print("Stack Underflow: Stack is empty!")
        return None
    return stack[-1]

# Demonstration:
stk = create_stack()
push(stk, 10)
push(stk, 20)
push(stk, 30)
print("Top element is:", peek(stk))  # 30
pop(stk)                             # Removes 30
pop(stk)                             # Removes 20
pop(stk)                             # Removes 10
pop(stk)                             # Stack Underflow Error!

3. Algorithmic Applications of Stacks

Understand & Deep Dive
A. String Reversal

To reverse a string $S$, push all characters sequentially onto a stack, then pop them one by one. Because of LIFO, the characters emerge in reverse order ($O(n)$ time complexity).

B. Balanced Parentheses Checking

Compilers verify syntax balance (e.g., in math or code) using a stack:

  • Scan the expression character by character from left to right.
  • Whenever an opening bracket (`(`, `{`, `[`) is encountered, push it onto the stack.
  • Whenever a closing bracket (`)`, `}`, `]`) is encountered:
    • If the stack is empty, report Unbalanced (closing bracket with no matching opener).
    • Else, pop the top bracket and verify if it matches the current closing bracket. If mismatched, report Unbalanced.
  • At the end of the string, if the stack is completely empty, the expression is Balanced; otherwise, unbalanced.

Key Programming Syntax, Statements & Translator Rules

Stack Time Complexity
$$T(\text{push}) = O(1), \quad T(\text{pop}) = O(1), \quad T(\text{peek}) = O(1)$$
Constant time access when using the end of a dynamic list as the TOP.
LIFO Property
$$\text{Exit Sequence}(e_1, e_2, \dots, e_n) = (e_n, e_{n-1}, \dots, e_1)$$
Exact inversion of arrival order.

Stack LIFO Primitive Operations Architecture

Stack Linear Data Structure (LIFO Discipline) 10 (Bottom) 20 30 ← TOP POINTER PUSH(40) Adds at TOP POP() → 30 Removes from TOP Closed Bottom (No insertions or deletions allowed) Single Accessible End: TOP • LIFO (Last-In, First-Out)

Chapter Summary & 10 Key Takeaways

Takeaway 1
A Stack is a linear data structure operating under the Last-In, First-Out (LIFO) access principle.
Takeaway 2
All additions and removals occur exclusively at a single accessible end called the TOP.
Takeaway 3
`push(item)` adds an element to the TOP; `pop()` removes and returns the top element.
Takeaway 4
`peek()` inspects the top item without removing it; `isEmpty()` checks if the stack has zero elements.
Takeaway 5
Stack Underflow occurs when attempting to pop or peek from an empty stack.
Takeaway 6
Stack Overflow occurs when pushing onto a full stack in bounded implementations.
Takeaway 7
In Python, stacks are efficiently implemented using lists with `lst.append()` as push and `lst.pop()` as pop.
Takeaway 8
Both push and pop operations run in $O(1)$ constant amortized time complexity.
Takeaway 9
Stacks power essential computational mechanisms: browser history, undo/redo, and recursion call stacks.
Takeaway 10
Compiler applications include parsing expressions, balanced parenthesis checking, and postfix evaluation.

Check Your Understanding (Diagnostic Practice Questions)

Diagnostic questions testing core conceptual clarity. Answers are hidden initially — solve each problem first, then click to reveal the step-by-step verified solution.

1
Explain the Last-In-First-Out (LIFO) principle of a Stack with a real-life physical analogy and a computing example.
Reveal Answer & Explanation
Answer: LIFO states that the most recently inserted element must be the very first element to be removed.
• Real-life physical analogy: A spring-loaded stack of cafeteria dinner plates. Clean plates are placed on top of the stack, and diners take the top plate first. The bottom plate remains until all others are removed.
• Computing example: Web browser "Back" button history. As you navigate from Page 1 → Page 2 → Page 3, URLs are pushed onto a stack. Clicking "Back" pops Page 3 first, returning you to Page 2.
Last item added is first item removed; plate stack or browser back button.
2
What are Stack Underflow and Stack Overflow? Write Python code to detect and prevent Stack Underflow.
Reveal Answer & Explanation
Answer: • Stack Underflow: An illegal condition where an algorithm attempts to pop or inspect an element from an empty stack (`len(stack) == 0`).
• Stack Overflow: An illegal condition where an algorithm attempts to push an item onto a full stack whose fixed capacity has been reached.
Python Prevention Code:
def safe_pop(stack):
    if len(stack) == 0:
        print("Stack Underflow Error: Stack is empty!")
        return None
    return stack.pop()

Underflow is popping from empty stack; check len(stack) == 0 before popping.
3
Why is it computationally preferred to use the end of a Python list as the TOP of a stack rather than the beginning (`index 0`)?
Reveal Answer & Explanation
Answer: In Python lists (which are dynamic arrays), appending (`lst.append()`) and popping from the end (`lst.pop()`) take $O(1)$ constant time because elements are added/removed at the end without moving any other elements. In contrast, if `index 0` were chosen as the TOP, every push (`lst.insert(0, item)`) and pop (`lst.pop(0)`) would require shifting all $n$ subsequent elements in memory by one position, resulting in an extremely slow $O(n)$ linear time complexity.
Operating at the end takes O(1) time; operating at index 0 requires shifting all elements (O(n)).
4
Given an initially empty stack, trace the state of the stack after each operation:
`push(15)`, `push(30)`, `pop()`, `push(45)`, `push(60)`, `pop()`, `peek()`.
Reveal Answer & Explanation
Answer:
  1. push(15) → Stack: [15] (TOP: 15)
    2. push(30) → Stack: [15, 30] (TOP: 30)
    3. pop() → Removes 30; Stack: [15] (TOP: 15)
    4. push(45) → Stack: [15, 45] (TOP: 45)
    5. push(60) → Stack: [15, 45, 60] (TOP: 60)
    6. pop() → Removes 60; Stack: [15, 45] (TOP: 45)
    7. peek() → Returns 45 without removing; Stack remains [15, 45].

Track stack contents after each push and pop from left to right.
5
Write a Python function `reverse_string(s)` that reverses any input string using an explicit stack data structure.
Reveal Answer & Explanation
Answer:
def reverse_string(s):
    stack = []
    for char in s:
        stack.append(char)  # Push characters
    reversed_str = ""
    while len(stack) > 0:
        reversed_str += stack.pop()  # Pop in LIFO order
    return reversed_str

print(reverse_string("TARGET"))  # Outputs: TEGRAT

Push all characters onto stack, then pop all characters to form reversed string.
6
Explain how the call stack functions during a recursive function execution in Python. What causes a `RecursionError`?
Reveal Answer & Explanation
Answer: Each time a function is called, the Python runtime allocates a new stack frame on the system call stack storing local variables, parameters, and the return address. In recursion, each recursive call pushes a new frame on top of previous frames. When base cases are reached, frames pop in LIFO order. If a recursive function lacks a valid base case, it calls itself endlessly, exhausting stack memory until Python raises a `RecursionError: maximum recursion depth exceeded`.
Recursive calls push stack frames; missing base cases cause stack overflow (RecursionError).
7
How does a stack verify whether an algebraic expression has balanced parentheses `()`? Describe the algorithm.
Reveal Answer & Explanation
Answer: Algorithm:
1. Initialize an empty stack.
2. Scan the expression from left to right.
3. If an opening parenthesis `(` is encountered, push it onto the stack.
4. If a closing parenthesis `)` is encountered, check if stack is empty (if so, return False); otherwise, pop the top element.
5. After scanning the whole string, return `True` if stack is empty, else `False`.
Push on "(", pop on ")"; verify stack is empty at the end.
8
Evaluate the postfix expression `5 3 + 2 * 4 -` using a stack. Show step-by-step trace.
Reveal Answer & Explanation
Answer:

Trace:
• Read 5: Push 5 → Stack: [5]
• Read 3: Push 3 → Stack: [5, 3]
• Read '+': Pop 3 and 5, compute $5 + 3 = 8$, push 8 → Stack: [8]
• Read 2: Push 2 → Stack: [8, 2]
• Read '*': Pop 2 and 8, compute $8 \times 2 = 16$, push 16 → Stack: [16]
• Read 4: Push 4 → Stack: [16, 4]
• Read '-': Pop 4 and 16, compute $16 - 4 = 12$, push 12 → Stack: [12]
Final result: 12.


Push numbers; on operator, pop top two operands, evaluate (op1 operator op2), and push result.
Finished Studying This Chapter?
READY TO PRACTICE?

Timed CBT Practice Tests (Exam Simulator)

Put your concepts to the test with official curriculum-aligned Foundation and Advanced practice tests. Get instant accuracy scores, time metrics, and step-by-step verified explanations.