CS205

Stack vs Queue Comparison

See how the same operations produce different results

Side-by-Side Comparison

Perform the same operations on both Stack and Queue to see how they behave differently.

Stack (LIFO)Last-In, First-Out
Stack is empty

Remove returns: most recently added

Queue (FIFO)First-In, First-Out
Queue is empty

Remove returns: first added (oldest)

Key Difference

After adding elements 1, 2, 3 in order:

  • Stack removes in order: 3, 2, 1 (reverse order - LIFO)
  • Queue removes in order: 1, 2, 3 (same order - FIFO)

Click "Demo: Add 1,2,3 then Remove All" to see this in action!

Complete Comparison
FeatureStackQueue
PrincipleLIFO (Last-In, First-Out)FIFO (First-In, First-Out)
Insert Operationpush() - adds to topenqueue() - adds to rear
Remove Operationpop() - removes from topdequeue() - removes from front
View Operationpeek() - views toppeek() - views front
Time ComplexityO(1) for all opsO(1) for all ops
Java InterfaceDeque<E> (preferred)Queue<E>
Java ImplementationArrayDeque, LinkedListLinkedList, ArrayDeque
AnalogyStack of platesLine at a store
Best ForUndo, backtracking, recursionScheduling, BFS, buffers
Decision Guide: Which One to Use?
Choose Stack When...
  • You need to reverse order
  • Most recent item matters most
  • Implementing undo/redo
  • Parsing expressions/brackets
  • Implementing DFS traversal
  • Converting recursion to iteration
Choose Queue When...
  • First-come, first-served matters
  • Processing in arrival order
  • Implementing task scheduling
  • Buffering data streams
  • Implementing BFS traversal
  • Level-order processing
Choose Priority Queue When...
  • Elements have different priorities/importance
  • Need to always process the "most important" item next
  • Implementing Dijkstra's or A* algorithms
  • Event-driven simulation (process earliest event first)
Real-World Examples

Stack Examples

🔙 Browser Back Button

Pages visited are pushed. Back button pops to show previous page.

↩️ Undo in Text Editors

Actions pushed to undo stack. Undo pops most recent action.

📞 Function Call Stack

Each function call pushes a frame. Return pops it.

Queue Examples

🖨️ Print Queue

Documents printed in order they were sent.

🎫 Customer Service

Customers served in order they arrived.

⚙️ Task Scheduler

CPU processes tasks in submission order (basic scheduling).

Key Takeaways

1.Stack = LIFO (think of a stack of plates)

2.Queue = FIFO (think of a waiting line)

3.Both have O(1) time for all basic operations

4.Use Stack for undo, backtracking, DFS

5.Use Queue for scheduling, buffering, BFS

6.Use PriorityQueue when order depends on priority