D

Learn Stacks and Queues in Python

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]

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]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top