Skip to content

Instantly share code, notes, and snippets.

@mridulgain
Created November 18, 2023 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mridulgain/1419d654781f66f9e3cbbe8ce04209b6 to your computer and use it in GitHub Desktop.
Save mridulgain/1419d654781f66f9e3cbbe8ce04209b6 to your computer and use it in GitHub Desktop.
stack implementation using python list
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