Python Snippets for Learning Stacks and Queues
Stacks
# Creating a Stack
stack = []
# Pushing elements
stack.append(3); stack.append(7); stack.append(5)
# Popping elements
stack.pop()
stack = []
# Pushing elements
stack.append(3); stack.append(7); stack.append(5)
# Popping elements
stack.pop()
# Checking if stack is empty
is_empty = not stack
is_empty = not stack
# Getting the top element without popping
top_element = stack[-1] if stack else None
top_element = stack[-1] if stack else None
# Size of the stack
size = len(stack)
size = len(stack)
# Clearing the stack
stack.clear()
stack.clear()
Queues
from collections import deque
# Creating a Queue
queue = deque()
# Enqueueing elements
queue.append(3); queue.append(7); queue.append(5)
# Creating a Queue
queue = deque()
# Enqueueing elements
queue.append(3); queue.append(7); queue.append(5)
# Dequeueing an element
if queue:
queue.popleft()
if queue:
queue.popleft()
# Checking if queue is empty
is_empty = not queue
is_empty = not queue
# Getting the front element without dequeueing
front_element = queue[0] if queue else None
front_element = queue[0] if queue else None
# Size of the queue
size = len(queue)
size = len(queue)