CS205

Stacks & Queues

Fundamental linear data structures with different access patterns

πŸ“šStack (LIFO)
Last-In, First-Out

Think of a stack of plates. You can only add or remove from the top. The last plate you put on is the first one you take off.

3 ← top
2
1

Operations: push (add to top), pop (remove from top), peek (view top)

πŸšΆβ€β™‚οΈQueue (FIFO)
First-In, First-Out

Think of a line at a store. The first person in line is the first to be served. New people join at the back.

front β†’
1
2
3
← rear

Operations: enqueue (add to rear), dequeue (remove from front), peek (view front)

When to Use Which?

Use a Stack when:

  • πŸ”™Undo/Redo - Most recent action should be undone first
  • 🌐Browser History - Back button goes to most recent page
  • πŸ“žFunction Calls - Most recent function returns first
  • πŸ”€Balanced Parentheses - Match most recent opening bracket
  • πŸ”„Reverse Order - Need to process in reverse

Use a Queue when:

  • πŸ–¨οΈPrint Queue - Documents print in order sent
  • ⏳Task Scheduling - First task submitted runs first
  • 🌳BFS Traversal - Explore level by level
  • 🎫Customer Service - First come, first served
  • πŸ“¨Message Buffers - Process messages in order
Quick Comparison
AspectStackQueue
OrderLIFO (Last-In, First-Out)FIFO (First-In, First-Out)
Insertpush() - at topenqueue() - at rear
Removepop() - from topdequeue() - from front
Viewpeek() - top elementpeek() - front element
Time ComplexityO(1) for all operationsO(1) for all operations
Java ClassStack<E> or Deque<E>Queue<E>, LinkedList<E>

Explore Topics