Skip to content

Commit

Permalink
Updated stack.py with examples and comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Charul00 committed Oct 2, 2024
1 parent 01fd3ad commit 0d07b8e
Showing 1 changed file with 35 additions and 13 deletions.
48 changes: 35 additions & 13 deletions Algorithms_and_Data_Structures/Stack/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,42 @@ def size(self):

# Example usage
if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)

print("Top element is:", stack.peek()) # Output: Top element is: 30
print("Stack size is:", stack.size()) # Output: Stack size is: 3
# Example with integers
int_stack = Stack()
int_stack.push(10)
int_stack.push(20)
int_stack.push(30)
print("Top element is:", int_stack.peek()) # Output: Top element is: 30
print("Stack size is:", int_stack.size()) # Output: Stack size is: 3
print("Popped element:", int_stack.pop()) # Output: Popped element: 30
print("Stack size after pop:", int_stack.size()) # Output: Stack size after pop: 2
print("Is stack empty?", int_stack.is_empty()) # Output: Is stack empty? False

print("Popped element:", stack.pop()) # Output: Popped element: 30
print("Stack size after pop:", stack.size()) # Output: Stack size after pop: 2
# Pop remaining elements
int_stack.pop() # Pops 20
int_stack.pop() # Pops 10
print("Is stack empty after popping all elements?", int_stack.is_empty()) # Output: Is stack empty after popping all elements? True

print("Is stack empty?", stack.is_empty()) # Output: Is stack empty? False
# Example with strings
string_stack = Stack()
string_stack.push("Hello")
string_stack.push("World")
print("Top element is:", string_stack.peek()) # Output: Top element is: World
print("Stack size is:", string_stack.size()) # Output: Stack size is: 2
print("Popped element:", string_stack.pop()) # Output: Popped element: World
print("Stack size after pop:", string_stack.size()) # Output: Stack size after pop: 1
print("Is stack empty?", string_stack.is_empty()) # Output: Is stack empty? False

stack.pop() # Pops 20
stack.pop() # Pops 10

print("Is stack empty after popping all elements?", stack.is_empty()) # Output: Is stack empty after popping all elements? True

# Top element is: 30
# Stack size is: 3
# Popped element: 30
# Stack size after pop: 2
# Is stack empty? False
# Is stack empty after popping all elements? True
# Top element is: World
# Stack size is: 2
# Popped element: World
# Stack size after pop: 1
# Is stack empty? False

0 comments on commit 0d07b8e

Please sign in to comment.