Lecture 16
Stacks
A stack is a last-in, first-out (LIFO) container. The three core operations are:
push(value)— add an element to the toppop()— remove the top elementtop()— read the top element without removing it
Think of a stack of plates: you can only add or remove from the top.
The top of the stack is data_[size_ - 1]. push appends at the end; pop decrements size_ — no
data is moved. grow doubles capacity when the array is full, copying existing elements.
Calling top() or pop() on an empty stack accesses data_[-1] — undefined behavior. Always
check empty() before calling them.
Queues
A queue is a first-in, first-out (FIFO) container. Elements enter at the back and leave from the front:
enqueue(value)— add an element to the backdequeue()— remove the front elementfront()— read the front element without removing it
Think of a line at a ticket counter: the first person in is the first person served.
enqueue appends a new node at tail_. dequeue removes the node at head_. The tail_ pointer
avoids walking the whole list to find the back — both operations are O(1).
When the last element is dequeued, both head_ and tail_ must be set to nullptr. Forgetting
to reset tail_ leaves a dangling pointer that corrupts the next enqueue.
Stack vs. Queue
| Stack | Queue | |
|---|---|---|
| Order | LIFO — last in, first out | FIFO — first in, first out |
| Add | push at top | enqueue at back |
| Remove | pop from top | dequeue from front |
| Typical use | undo history, call stack | task scheduling, BFS |
Exercises
Q1.
Without running the code, predict what this program prints.
Q2.
Without running the code, trace the queue's front and back after each operation and predict the output.
Q3.
Each snippet has a bug related to stacks or queues. Identify what's wrong.
Q4.
Implement push, pop, and top for the array-backed stack below.
Q5.
Implement enqueue, dequeue, and front for the linked-list queue below.
Practice Problems
- Valid Parentheses — Easy
- Number of Recent Calls — Easy
- Implement Queue using Stacks — Easy
- Daily Temperatures — Medium