Back to Data Structures

Stacks & Queues

LIFO vs FIFO ordering

Ordering Matters

Stacks and queues are abstract data types that define how elements are added and removed. Stacks follow LIFO (Last In, First Out)—like a stack of plates. Queues follow FIFO (First In, First Out)—like a line at a store.

Use Stacks For:

  • • Undo/Redo functionality
  • • Function call management
  • • Expression parsing (parentheses)
  • • Backtracking algorithms (DFS)

Use Queues For:

  • • Task scheduling
  • • Print job management
  • • BFS traversal
  • • Message buffers

Stack

(Last In, First Out)
Top (push/pop here)
10
25
37
Bottom

Complexity Comparison

OperationStackQueue
Push / EnqueueO(1)O(1)
Pop / DequeueO(1)O(1)
Peek (Top/Front)O(1)O(1)
SearchO(n)O(n)

Both stacks and queues have O(1) for their primary operations. The choice depends entirely on the ordering you need: LIFO or FIFO.