|  | 
|  | 1 | + | 
|  | 2 | +class Stack: | 
|  | 3 | + | 
|  | 4 | + def __init__(self) -> None: | 
|  | 5 | + """ | 
|  | 6 | + Initializes the stack. | 
|  | 7 | + """ | 
|  | 8 | + | 
|  | 9 | + self.stack = [] | 
|  | 10 | + self.top = -1 | 
|  | 11 | + | 
|  | 12 | + def push(self, data) -> None: | 
|  | 13 | + """ | 
|  | 14 | + Pushes an element onto the stack. | 
|  | 15 | + """ | 
|  | 16 | + | 
|  | 17 | + self.stack.append(data) | 
|  | 18 | + self.top += 1 | 
|  | 19 | + | 
|  | 20 | + def peek(self): | 
|  | 21 | + """ | 
|  | 22 | + Returns the top of the stack element. | 
|  | 23 | + """ | 
|  | 24 | + | 
|  | 25 | + return self.stack[self.top] | 
|  | 26 | + | 
|  | 27 | + def pop(self): | 
|  | 28 | + """ | 
|  | 29 | + Pops the top element from the stack. | 
|  | 30 | + """ | 
|  | 31 | + | 
|  | 32 | + if not self.is_empty(): | 
|  | 33 | + elm = self.stack.pop() | 
|  | 34 | + self.top -= 1 | 
|  | 35 | + | 
|  | 36 | + return elm | 
|  | 37 | + else: | 
|  | 38 | + print('Stack is empty') | 
|  | 39 | + | 
|  | 40 | + def is_empty(self) -> bool: | 
|  | 41 | + """ | 
|  | 42 | + Returns whether the stack is empty or not. | 
|  | 43 | + """ | 
|  | 44 | + | 
|  | 45 | + return self.top < 0 | 
|  | 46 | + | 
|  | 47 | + def get_stack(self) -> list: | 
|  | 48 | + """ | 
|  | 49 | + Returns the complete stack. | 
|  | 50 | + """ | 
|  | 51 | + | 
|  | 52 | + return self.stack | 
|  | 53 | + | 
|  | 54 | +if __name__ == '__main__': | 
|  | 55 | + | 
|  | 56 | + stack = Stack() | 
|  | 57 | + | 
|  | 58 | + print('Pushing 2 onto the stack...') | 
|  | 59 | + stack.push(2) | 
|  | 60 | + print('Pushing 3 onto the stack...') | 
|  | 61 | + stack.push(3) | 
|  | 62 | + print('Stack Contents:', stack.get_stack()) | 
|  | 63 | + print('Top of the stack:', stack.peek()) | 
|  | 64 | + print('Popping top element...') | 
|  | 65 | + stack.pop() | 
|  | 66 | + print('Stack Contents:', stack.get_stack()) | 
|  | 67 | + print('Pushing 1 onto the stack...') | 
|  | 68 | + stack.push(1) | 
|  | 69 | + print('Stack Contents:', stack.get_stack()) | 
|  | 70 | + | 
|  | 71 | +# Result: | 
|  | 72 | +# --- | 
|  | 73 | +# | 
|  | 74 | +# Pushing 2 onto the stack... | 
|  | 75 | +# Pushing 3 onto the stack... | 
|  | 76 | +# Stack Contents: [2, 3] | 
|  | 77 | +# Top of the stack: 3 | 
|  | 78 | +# Popping top element... | 
|  | 79 | +# Stack Contents: [2] | 
|  | 80 | +# Pushing 1 onto the stack... | 
|  | 81 | +# Stack Contents: [2, 1] | 
0 commit comments