Created
November 18, 2023 16:37
-
-
Save mridulgain/1419d654781f66f9e3cbbe8ce04209b6 to your computer and use it in GitHub Desktop.
stack implementation using python list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. Cannot pop.") | |
def peek(self): | |
if not self.is_empty(): | |
return self.items[-1] | |
else: | |
print("Stack is empty. Cannot peek.") | |
def size(self): | |
return len(self.items) | |
# Example usage: | |
stack = Stack() | |
stack.push(1) | |
stack.push(2) | |
stack.push(3) | |
print("Stack:", stack.items) | |
print("Peek:", stack.peek()) | |
popped_item = stack.pop() | |
print("Popped:", popped_item) | |
print("Stack after pop:", stack.items) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment