Today , let’s understand Stacks and Queues in detail:

πŸ“¦ What is a Stack?
Think of a stack like a stack of plates:

  • You add a new plate on top
  • You remove the plate from the top
    This is called LIFO β†’ Last In, First Out

Key Operations:
βœ… push() β†’ Add an item to the top
βœ… pop() β†’ Remove the top item
βœ… peek() β†’ See the top item without removing
βœ… isEmpty() β†’ Check if the stack is empty

Real-Life Examples:

  • Undo in a text editor
  • Browser back button
  • Recursion calls

Example in Code (JavaScript):
js
let stack = [];

stack.push(1); // Add 1
stack.push(2); // Add 2
stack.pop(); // Removes 2
console.log(stack); // [1]

πŸŒ€ What is a Queue?
A queue works like a line at the supermarket:

  • The first person in line is served first
    This is called FIFO β†’ First In, First Out

Key Operations:
βœ… enqueue() β†’ Add to the end
βœ… dequeue() β†’ Remove from the front
βœ… peek() β†’ See who’s first
βœ… isEmpty() β†’ Check if queue is empty

Real-Life Examples:

  • Waiting list
  • Print queue
  • Customer service calls

Example in Code (JavaScript):
js
let queue = [];

queue.push(“A”); // Enqueue A
queue.push(“B”); // Enqueue B
queue.shift(); // Dequeue A
console.log(queue); // [“B”]


πŸ”„ Advanced Types

  • Circular Queue β†’ Saves space by reusing empty spots
  • Deque β†’ Add/remove from both ends
  • Priority Queue β†’ Items come out based on importance, not just order

βœ… When to Use

  • Stack: When you need to reverse something or go back
  • Queue: When you need to process in order, like first come, first served

React ❀️ for more

LEAVE A REPLY

Please enter your comment!
Please enter your name here