Revision Notes on Stacks for Class 12 Computer Science

 Revision Notes on Stacks for Class 12 Computer Science. This topic usually guarantees a 3-Mark Coding Question in Section C.


1. What is a Stack?

  • Definition: A linear data structure that follows the LIFO (Last In, First Out) principle.

  • Analogy: A stack of plates or a coin holder. The last item put in is the first one taken out.

  • Insertion & Deletion: Both happen at the same end, known as the TOP.

  • Shutterstock

2. Key Terminology

  1. Push: Adding an element to the top of the stack.

  2. Pop: Removing an element from the top of the stack.

  3. Peek (or Top): Viewing the topmost element without removing it.

  4. Underflow: Trying to Pop from an empty stack. (Error condition).

  5. Overflow: Trying to Push into a full stack. (Rare in Python as lists are dynamic, but theoretically important).


3. Python Implementation (Using Lists)

In CBSE Class 12, we use a standard Python List to simulate a Stack.

Stack OperationPython List MethodComplexity
Pushlist.append(item)O(1)
Poplist.pop()O(1)
Peeklist[-1]O(1)
IsEmptylen(list) == 0 or list == []O(1)

4. Exam Coding Patterns (Memorize These!)

The Board Exam usually asks you to write Push and Pop functions for a specific scenario (e.g., a stack of Books, Employees, or Numbers).

Scenario A: Stack of Numbers (Simple)

Python
def Push(Stack, item):
    Stack.append(item)  # Adds to the end (Top)

def Pop(Stack):
    if len(Stack) == 0: # OR if Stack == []:
        return "Underflow"  # Stack is empty
    else:
        return Stack.pop()  # Removes the last element

Scenario B: Stack of Dictionaries (High Probability)

Question: Write Push/Pop functions to manage a stack of Students, where each student has a RollNo and Name.

Python
# Function to Add a Student
def Push_Student(Stk):
    r = int(input("Enter Roll No: "))
    n = input("Enter Name: ")
    rec = [r, n]  # OR rec = {'Roll': r, 'Name': n}
    Stk.append(rec)

# Function to Delete a Student
def Pop_Student(Stk):
    if len(Stk) == 0:
        print("Stack Empty! (Underflow)")
    else:
        val = Stk.pop()
        print("Deleted Student:", val)

# Function to Display Stack (Top to Bottom)
def Display(Stk):
    if len(Stk) == 0:
        print("Empty")
    else:
        # Loop backwards from last index to 0
        for i in range(len(Stk)-1, -1, -1):
            print(Stk[i])

Scenario C: Push only specific items

Question: Push only numbers divisible by 5 from a list N into a stack S.

Python
def Push_Five(N):
    S = []
    for num in N:
        if num % 5 == 0:
            S.append(num)
    return S

5. Application: Infix to Postfix Expressions

While you rarely have to code this, you might get a 1-mark question or a logic question on Evaluation of Postfix.

Evaluation Logic (for Postfix like 4 5 +):

  1. Scan expression left to right.

  2. If Operand (Number): PUSH to Stack.

  3. If Operator (+, -, *, /):

    • POP two elements (A and B).

    • Calculate B operator A (Note: The one popped second is the first operand).

    • PUSH result back.

  4. Final answer is the only item left in Stack.


6. Common Mistakes to Avoid

  1. Popping without checking Empty: Always write if len(Stack)==0 before using pop().

  2. Displaying incorrectly: A stack must be displayed from Top to Bottom (End of list to Start). Do not use a normal for x in list loop; use range(len(S)-1, -1, -1) or list[::-1].

  3. Variable Scope: In functions, lists are mutable. You don't strictly need return if you modify the list in place, but it is good practice depending on the question syntax.

Quick Test

Q: Given Stack = [10, 20, 30].

  1. Stack.pop()

  2. Stack.append(40)

  3. print(Stack[-1])

Output: 40 (Explanation: 30 is popped. Stack becomes [10, 20]. 40 is appended. Stack becomes [10, 20, 40]. Top is 40).

Comments

Popular Posts