Use a stack when the most recently added item must be processed first. Use a queue when items must be processed in the same order in which they arrived.
The Reasoning
A stack follows LIFO (last in, first out). Items are added using push and removed using pop, both at the top of the stack. This makes a stack suitable when processing must reverse the order of arrival or return to a previous state.
For example, a browser can push each visited page onto a stack. Selecting “Back” pops the most recently visited page first. Function calls also use a call stack, allowing the most recently called function to finish before control returns to the earlier function.
A queue follows FIFO (first in, first out). Items are added at the rear using enqueue and removed from the front using dequeue. This preserves arrival order and is appropriate for fair, sequential processing.
| Data structure | Use it when | Typical applications |
|---|---|---|
| Stack | The newest item must be processed first | Undo operations, browser history, function calls, depth-first search |
| Queue | The oldest item must be processed first | Print jobs, customer requests, task scheduling, breadth-first search |
Suppose print jobs A, B, and C arrive in that order. A queue processes A, then B, then C. A stack would process C, then B, then A, so it would not normally be appropriate for fair print scheduling.
A common misconception is that stacks and queues store different types of data. They can store the same data; the difference is the order of access and the operations permitted.
Exam Technique
For an IB question using compare, state both the similarity and the difference: both are linear data structures, but stacks use LIFO while queues use FIFO. For justify, connect the required processing order to the correct structure and name its operations rather than merely giving an example.