-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
59 lines (50 loc) · 1.44 KB
/
stack.py
File metadata and controls
59 lines (50 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty")
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
print("Stack is empty")
return None
def size(self):
return len(self.items)
# Create a stack object
stack = Stack()
# Main loop for stack operations
while True:
print("\nSelect operation:")
print("1. Push")
print("2. Pop")
print("3. Show elements")
print("4. Empty the stack")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("\nEnter element to push: ")
stack.push(item)
print("Element pushed onto the stack:", item)
elif choice == '2':
popped_item = stack.pop()
if popped_item is not None:
print("Popped element from the stack:", popped_item)
elif choice == '3':
print("\nElements in STACK:", stack.items)
elif choice == '4':
stack.items = []
print("\nStack emptied")
elif choice == '5':
print("\nExiting program")
break
else:
print("\nInvalid choice. Please enter a number from 1 to 5.")