Programming Resources | Python | Javascript | Artificial Intelligence Updates | Computer Science Courses | AI Books
56.2K subscribers
878 photos
3 videos
4 files
343 links
Everything about programming for beginners
* Python programming
* Java programming
* App development
* Machine Learning
* Data Science

Managed by: @love_data
Download Telegram
Core Data Structures Part 2 – Stacks Queues 📚📥📤

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
3