Stack
Stack
Source Code:
class Stack:
def init (self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty, cannot pop from an empty stack")
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
print("Stack is empty, cannot peek from an empty stack")
return None
def display(self):
if not self.is_empty():
print(self.items)
else:
print("Stack is empty")
stack = Stack()
if choice == 1:
item = input("Enter the item to push: ")
stack.push(item)
elif choice == 2:
popped_item = stack.pop()
if popped_item is not None:
print("Popped item:", popped_item)
elif choice == 3:
top_item = stack.peek()
if top_item is not None:
print("Top item:", top_item)
elif choice == 4:
stack.display()
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 03
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 18
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the item to push: 07
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
['03', '18', '07']
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped item: 07
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top item: 18
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
['03', '18']
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 5
Exiting the program.