HomeComputer SciencePracticalClass 12Stack Implementation

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

Stack Implementation

AIM

To write a Python program to implement a stack data structure.

ALGORITHM

  1. Start
  2. Define a class Stack with methods push, pop, and is_empty
  3. Implement the push method to add elements to the stack
  4. Implement the pop method to remove elements from the stack
  5. Implement the is_empty method to check if the stack is empty
  6. Stop

PROGRAM

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return None

    def is_empty(self):
        return len(self.items) == 0

# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())  # Output: 3
print(stack.pop())  # Output: 2
print(stack.is_empty())  # Output: False
print(stack.pop())  # Output: 1
print(stack.is_empty())  # Output: True

OUTPUT

3

2

False

1

True

CONCLUSION

Thus, the given program was successfully executed and the output was verified as per the expected result.

VIVA QUESTIONS

  1. What are arithmetic operators in Python?

    Arithmetic operators are symbols used to perform mathematical operations: +, -, *, /, %, //, and **.

  2. What is a stack in computer science?

    A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.

  3. How do you implement a stack in Python?

    You can implement a stack in Python using a list with methods like append for push and pop for pop operations.