What is a queue and a stack, and when do you use each?
Two of the simplest data structures, distinguished entirely by which element you get back: a stack returns the most recently added, a queue returns the oldest. That single difference determines an enormous range of behaviour.
A stack is last in, first out. Push onto the top, pop from the top. Think of a pile of plates.
Where stacks appear: the call stack, holding function frames, which is why the data structure and the error share a name; undo history, where the most recent action is reversed first; expression evaluation and bracket matching; depth-first traversal of trees and graphs; and backtracking algorithms.
A queue is first in, first out. Enqueue at the back, dequeue from the front. Think of a line of people.
Where queues appear: task and job processing, where fairness matters; breadth-first traversal, which finds shortest paths in unweighted graphs; buffering between a fast producer and a slow consumer; request handling; and print and message queues.
The traversal point is the clearest illustration. Depth-first and breadth-first search are the same algorithm with the same structure — the only difference is whether pending nodes are held in a stack or a queue. Swapping one for the other changes the entire character of the search.
The variants worth knowing:
Deque, allowing insertion and removal at both ends, which can act as either.
Priority queue, returning the highest-priority element rather than the oldest — implemented with a heap, and the basis of scheduling and of shortest-path algorithms.
Circular buffer, a fixed-size queue that overwrites the oldest entry when full, used in logging and audio processing where bounded memory matters more than completeness.
What to watch for in practice: unbounded queues, which convert a throughput problem into an out-of-memory crash and hide the fact that consumers cannot keep up; and deep recursion, which is a stack that will eventually overflow.
In most languages you will not implement either — a dynamic array serves as a stack, and standard libraries provide efficient deques and priority queues.