Applications of Stacks and Queues: Call Stacks, Undo, Buffers and Breadth-First Traversal
IB Computer Science · Abstract Data Structures (HL)
Choose by what must come out first. A stack returns the item added most recently (last in, first out); a queue returns the item added earliest (first in, first out). Every application question reduces to one question: which item must be dealt with first, the newest or the oldest? Answer that and the structure follows. Both are usually built on an array or a linked list, and both offer only a handful of operations — push and pop, or enqueue and dequeue, plus a test for empty — which is exactly what makes them safe: the caller cannot reach into the middle.
Stack applications. The call stack: when a sub-program calls another, the return address and local variables are pushed; when it finishes they are popped, so the most recently called sub-program always finishes first — this is what makes recursion possible, and what overflows when recursion is too deep. Undo: each action is pushed; undo pops the most recent; redo needs a second stack. Expression evaluation: postfix expressions are evaluated by pushing operands and popping two for each operator; compilers convert infix to postfix using a stack of operators. Browser back button, bracket matching and depth-first traversal of a tree or maze are the same pattern: the most recent choice is the first to revisit.
Queue applications. The print queue: documents are printed in the order submitted. Buffers: a keyboard buffer stores keystrokes until the program reads them; a router queues packets until the outgoing link is free; a video player buffers frames so that playback stays smooth when the network hiccups — in every case the producer and consumer run at different speeds and the queue absorbs the difference while preserving order. Process scheduling keeps ready processes in a queue. Breadth-first traversal of a tree uses a queue: enqueue the root; repeatedly dequeue a node, visit it, and enqueue its children; the result is level by level, left to right. Replace the queue with a stack in the same algorithm and the traversal becomes depth-first — the clearest demonstration that the structure, not the loop, decides the order.
Implementation details that get asked. A queue in a plain array creeps to the right as items are removed from the front, wasting space or forcing every element to shift; a circular queue lets the front and rear pointers wrap around, so both operations are constant time in a fixed array. A stack in an array needs only a top index. Linked-list versions grow without limit but cost a pointer per item. Both structures must handle empty (pop or dequeue on nothing) and, in array form, full — and an exam answer that omits these checks loses marks.
Worked example: Example 1 — designing undo and redo for a text editor
A text editor needs undo (Ctrl+Z) and redo (Ctrl+Y). Choose a structure and describe the operation for each event: the user types, the user undoes, the user redoes, the user types something new after undoing. State how to handle a memory limit of 100 operations.
Solution
Structure. Two stacks: UNDO and REDO. Undo must cancel the most recent operation first, so UNDO is a stack; redo must restore the most recently undone operation first, so REDO is also a stack.
The user types. Push a description of the operation (position, inserted character) onto UNDO. At the same time clear REDO completely: after doing something new, the old redo chain is no longer valid — omitting this step is the classic error that makes redo insert text in the wrong place.
Undo. If UNDO is empty, do nothing (the empty check is mandatory). Otherwise pop one operation, reverse it on the text (delete the inserted character), then push it onto REDO.
Redo. If REDO is empty, do nothing. Otherwise pop from REDO, reapply it to the text, and push it back onto UNDO. The two stacks move operations back and forth, and the text is always consistent with the top of UNDO.
Typing something new after undoing. This is exactly the first case: push onto UNDO and clear REDO. If you do not clear it, the user could redo an operation based on a text state that no longer exists.
The limit of 100 operations. A pure stack can only discard at the top, but when full we need to discard the oldest operation at the bottom. The solution is to implement UNDO on a circular array of size 100: when pushing while full, the bottom is overwritten and the bottom pointer advances. That is, the actual structure is a bounded stack that discards from the bottom — a hybrid of a stack and a circular queue, and a good answer names this instead of saying stack and stopping.
Worked example: Example 2 — choosing a queue or a stack for three system situations
Choose a structure and explain: (a) a router receiving packets faster than the outgoing line speed; (b) a web browser managing the back button; (c) a robot finding the shortest path out of a grid maze, moving one cell per step. For (c), what happens if you use the other structure?
Solution
(a) Router — a queue. The packet that arrives first must go first, to keep the order and so that no packet is starved; the queue absorbs the speed difference between the incoming and outgoing lines. When the queue is full, the router drops newly arriving packets, and TCP at the two ends detects the loss and slows down — a full queue is itself the congestion signal. Implement it with a circular queue in fixed memory because a router must not allocate dynamically while busy.
(b) Back button — a stack. The page left most recently is the page to return to first. Each time you go to a new page, push the current page; going back is a pop. Like undo, a second stack is needed for the forward button, and going to a new page after going back must clear the forward stack.
(c) Maze, shortest path — a queue. Enqueue the starting cell; repeatedly remove a cell, mark it visited, and enqueue its unvisited neighbors. Because the queue processes in the order of insertion, every cell 1 step from the start is processed before every cell 2 steps away, and so on — so the first time the goal cell is reached is via the shortest path. This is breadth-first traversal, and the shortest property comes from expanding in concentric rings.
If a stack is used for (c). The algorithm still finds the exit if there is one, but it goes deep along one branch to the end before trying another, so the path found may be much longer than the shortest; it uses less memory on a wide maze because it keeps only one branch, and it is the right choice when you need just any exit. With the same loop, changing the structure changes the algorithm's promise — from shortest to any.
Common mistake
Trap 1 — forgetting to clear the redo stack on a new action. Redo would then be applied to a state that no longer exists.Trap 2 — not checking for empty and full. Popping an empty stack and enqueuing into a full array are the exam errors that lose the most marks.
Trap 3 — saying breadth-first traversal is a different algorithm. The loop is the same; only the queue or stack decides level-order or depth-first.