Write a python program to implement Stack.
Added 2 weeks ago
Active
Viewed 26
Ans

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

    # Push an element onto the stack
    def push(self, item):
        self.stack.append(item)
        print(f"Pushed: {item}")

    # Pop an element from the stack
    def pop(self):
        if not self.is_empty():
            item = self.stack.pop()
            print(f"Popped: {item}")
            return item
        else:
            print("Stack is empty. Nothing to pop.")
            return None

    # Peek at the top element
    def peek(self):
        if not self.is_empty():
            return self.stack[-1]
        else:
            print("Stack is empty.")
            return None

    # Check if the stack is empty
    def is_empty(self):
        return len(self.stack) == 0

    # Display the stack
    def display(self):
        if self.is_empty():
            print("Stack is empty.")
        else:
            print("Stack (top to bottom):")
            for item in reversed(self.stack):
                print(item)

# Example usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
s.display()

print("Top element is:", s.peek())

s.pop()
s.display()

Sample Output:

Pushed: 10
Pushed: 20
Pushed: 30
Stack (top to bottom):
30
20
10
Top element is: 30
Popped: 30
Stack (top to bottom):
20
10


Related Questions