DSA

Stack and Queue

Another linear data structure

What are Stack and Queue?

Both Stack and Queue are linear data structures used to store and manage collections of elements in a particular order.

By "in order," I mean that both Stack and Queue follow specific rules for how elements are added and removed.

Order in Stack (LIFO - Last In, First Out)

  • The last element you add is the first one to be removed.
  • Example:
Push A → [A]
Push B → [A, B]
Push C → [A, B, C]
Pop → Removes C → [A, B]
Pop → Removes B → [A]

Order in Queue (FIFO - First In, First Out)

  • The first element you add is the first one to be removed.
  • Example:
Enqueue A → [A]
Enqueue B → [A, B]
Enqueue C → [A, B, C]
Dequeue → Removes A → [B, C]
Dequeue → Removes B → [C]

Why do we have these linear data structures?

Both stack and queue help in managing data efficiently where ordering is important.

When to Use Stack vs Queue?

  • Use a Stack when you need to reverse things e.g., function calls (recursion), Backtracking (Maze Solving, Browser History).
  • Use a Queue when you need to process items in order e.g., task scheduling, event handling, API calls.

On this page