HomeComputer SciencePracticalClass 12Stack using List

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 using List

AIM

To write a Python program to implement stack data structure using list with push, pop, and display operations.

ALGORITHM

  1. Start
  2. Initialize an empty list as stack
  3. Define push() function to add elements to stack
  4. Define pop() function to remove elements from stack
  5. Define display() function to show stack contents
  6. Create menu-driven interface
  7. Perform operations based on user choice
  8. Stop

PROGRAM

class Stack:
    def __init__(self):
        self.stack = []
    
    def push(self, item):
        """Add an element to the top of stack"""
        self.stack.append(item)
        print(f"Pushed {item} to stack")
    
    def pop(self):
        """Remove and return the top element from stack"""
        if self.is_empty():
            print("Stack is empty! Cannot pop.")
            return None
        else:
            item = self.stack.pop()
            print(f"Popped {item} from stack")
            return item
    
    def peek(self):
        """Return the top element without removing it"""
        if self.is_empty():
            print("Stack is empty!")
            return None
        else:
            return self.stack[-1]
    
    def is_empty(self):
        """Check if stack is empty"""
        return len(self.stack) == 0
    
    def size(self):
        """Return the size of stack"""
        return len(self.stack)
    
    def display(self):
        """Display all elements in stack"""
        if self.is_empty():
            print("Stack is empty!")
        else:
            print("Stack contents (top to bottom):")
            for i in range(len(self.stack) - 1, -1, -1):
                print(f"| {self.stack[i]} |")
            print("+---+")

def main():
    stack = Stack()
    
    while True:
        print("\n--- Stack Operations ---")
        print("1. Push")
        print("2. Pop")
        print("3. Peek")
        print("4. Display")
        print("5. Size")
        print("6. Exit")
        
        choice = input("Enter your choice (1-6): ")
        
        if choice == '1':
            item = input("Enter element to push: ")
            stack.push(item)
        
        elif choice == '2':
            stack.pop()
        
        elif choice == '3':
            top = stack.peek()
            if top is not None:
                print(f"Top element: {top}")
        
        elif choice == '4':
            stack.display()
        
        elif choice == '5':
            print(f"Stack size: {stack.size()}")
        
        elif choice == '6':
            print("Exiting...")
            break
        
        else:
            print("Invalid choice! Please try again.")

if __name__ == "__main__":
    main()

OUTPUT

--- Stack Operations ---

1. Push

2. Pop

3. Peek

4. Display

5. Size

6. Exit

Enter your choice (1-6): 1

Enter element to push: 10

Pushed 10 to stack

Enter your choice (1-6): 4

Stack contents (top to bottom):

| 10 |

+---+

CONCLUSION

Thus, the stack data structure was successfully implemented using Python list with all basic operations.

VIVA QUESTIONS

  1. What is a stack data structure?

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

  2. What are the main operations of a stack?

    Push (insert), Pop (delete), Peek/Top (view top element), isEmpty, and Size.

  3. What is stack overflow and underflow?

    Overflow occurs when pushing to a full stack, underflow occurs when popping from an empty stack.