-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack-Operation.py
More file actions
39 lines (34 loc) · 805 Bytes
/
Stack-Operation.py
File metadata and controls
39 lines (34 loc) · 805 Bytes
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
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed {item} onto the stack.")
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"Popped {item} from the stack.")
return item
else:
print("Stack is empty. Cannot pop.")
return None
def is_empty(self):
return len(self.stack) == 0
def peek(self):
if not self.is_empty():
print(f"Top item is {self.stack[-1]}")
return self.stack[-1]
else:
print("Stack is empty.")
return None
# Example Usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
s.peek()
s.pop()
s.peek()
s.pop()
s.pop()
s.pop()