0% found this document useful (0 votes)
2 views

Program_8 Compiler

Uploaded by

kingadvert097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Program_8 Compiler

Uploaded by

kingadvert097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Q#8. Write a program to show the operations of stack.

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

return self.items.pop() if self.items else "Stack is empty"

def peek(self):

return self.items[-1] if self.items else "Stack is empty"

def display(self):

return self.items

# Demonstrate stack operations

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

print("Stack after pushing 1, 2, 3:", stack.display())

print("Peek top item:", stack.peek())

print("Popped item:", stack.pop())

print("Stack after popping an item:", stack.display())

print("Popped item:", stack.pop())

print("Popped item:", stack.pop())

print("Popped item (should be empty):", stack.pop())

print("Stack after popping all items:", stack.display())


Output:
Stack after pushing 1, 2, 3: [1, 2, 3]

Peek top item: 3

Popped item: 3

Stack after popping an item: [1, 2]

Popped item: 2

Popped item: 1

Popped item (should be empty): Stack is empty

Stack after popping all items: []

You might also like