Python Snippets for Learning Stacks and Queues
Stack
# Creating a Stack
stack = []
# Pushing elements onto the Stack
stack.append(3)
stack.append(7)
stack.append(5)
print(“Stack after Push:”, stack) # Output: [3, 7, 5]
# Popping elements from the Stack
stack.pop()
print(“Stack after Pop:”, stack) # Output: [3, 7]
stack = []
# Pushing elements onto the Stack
stack.append(3)
stack.append(7)
stack.append(5)
print(“Stack after Push:”, stack) # Output: [3, 7, 5]
# Popping elements from the Stack
stack.pop()
print(“Stack after Pop:”, stack) # Output: [3, 7]
Queue
from collections import deque
# Creating a Queue
queue = deque()
# Enqueueing elements into the Queue
queue.append(3)
queue.append(7)
queue.append(5)
print(“Queue after Enqueue:”, list(queue)) # Output: [3, 7, 5]
# Dequeueing elements from the Queue
queue.popleft()
print(“Queue after Dequeue:”, list(queue)) # Output: [7, 5]
# Creating a Queue
queue = deque()
# Enqueueing elements into the Queue
queue.append(3)
queue.append(7)
queue.append(5)
print(“Queue after Enqueue:”, list(queue)) # Output: [3, 7, 5]
# Dequeueing elements from the Queue
queue.popleft()
print(“Queue after Dequeue:”, list(queue)) # Output: [7, 5]