Stack Operations & Implementation

The stack is a linear data structure which follows the Last In First Out (LIFO) principle, where the last element added is the first one to be removed.

Core Operations:

Example Stack Implementation Using Array in Python:

class Stack:
    def __init__(self, capacity):
        self.stack = [None] * capacity
        self.top = -1
        self.capacity = capacity

    def is_empty(self):
        return self.top == -1

    def is_full(self):
        return self.top == self.capacity - 1

    def push(self, data):
        if self.is_full():
            print("Stack Overflow")
            return
        self.top += 1
        self.stack[self.top] = data

    def pop(self):
        if self.is_empty():
            print("Stack Underflow")
            return None
        data = self.stack[self.top]
        self.top -= 1
        return data

    def peek(self):
        if self.is_empty():
            return None
        return self.stack[self.top]

# Usage example:
s = Stack(5)
s.push(10)
s.push(20)
s.push(30)
print("Top element:", s.peek())
print("Popped element:", s.pop())
print("Top element after pop:", s.peek())

Advantages of Stack: