Stacks and queues are fundamental linear data structures used in many algorithms and real-world applications like undo operations, task scheduling, and more.
1๏ธโฃ What is a Stack?
A Stack is a Last-In-First-Out (LIFO) structure.
Think of a stack of plates: you add (push) and remove (pop) from the top.
Operations:
โข push(item) โ Add item to the top
โข pop() โ Remove item from the top
โข peek() โ View top item without removing
โข is_empty() โ Check if stack is empty
Python Implementation (Using List)
stack = []
# Push
stack.append(10)
stack.append(20)
# Pop
print(stack.pop()) # 20
# Peek
print(stack[-1]) # 10
# Check empty
print(len(stack) == 0)
2๏ธโฃ What is a Queue?
A Queue is a First-In-First-Out (FIFO) structure.
Think of a line at a ticket counter: first come, first served.
Operations:
โข enqueue(item) โ Add item to the rear
โข dequeue() โ Remove item from the front
โข peek() โ View front item
โข is_empty() โ Check if queue is empty
Python Implementation (Using collections.deque)
from collections import deque
queue = deque()
# Enqueue
queue.append(10)
queue.append(20)
# Dequeue
print(queue.popleft()) # 10
# Peek
print(queue[0]) # 20
# Check empty
print(len(queue) == 0)
3๏ธโฃ Stack Using Linked List (Python)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if not self.top:
return None
data = self.top.data
self.top = self.top.next
return data
4๏ธโฃ Queue Using Linked List (Python)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
def enqueue(self, data):
node = Node(data)
if not self.rear:
self.front = self.rear = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
if not self.front:
return None
data = self.front.data
self.front = self.front.next
if not self.front:
self.rear = None
return data
๐ Practice Tasks
1. Implement a stack using a list
2. Implement a queue using a list
3. Reverse a string using a stack
4. Check for balanced parentheses using a stack
5. Simulate a queue using two stacks
Double Tap โฅ๏ธ For More