3.2.5 · D3Linear Data Structures

Worked examples — Stack — LIFO semantics, push - pop - peek, array and linked list implementations

2,062 words9 min readBack to topic

This page is the "no scenario left behind" companion to the Stack topic note. We will hunt down every kind of situation a stack can hit — normal, empty, full, degenerate, and the tricky exam twist — and work each one all the way through.


The scenario matrix

Every cell below is a distinct case class this topic can throw at you. The examples afterward each hit one or more cells (labelled [Cell N]).

# Case class Trigger / degenerate input What could go wrong
1 Normal interleaved push/pop mixed sequence wrong LIFO read-off
2 Empty-stack operation pop/peek on top == -1 or head is None underflow crash
3 Full fixed array push when top == cap-1 overflow crash
4 Single element (boundary) one push then pop off-by-one at top = 0
5 Empty → dynamic growth linked list, no capacity never overflows
6 Order-of-operations bug pop = read-then-shrink; push wiring corrupt / self-loop
7 Real-world word problem undo history / browser back model choice
8 Multi-type nesting (exam twist) ([)] vs ([]) counter fails, stack needed

Example 1 — Normal interleaved trace [Cell 1]

Figure — Stack — LIFO semantics, push - pop - peek, array and linked list implementations

Example 2 — Popping / peeking an empty stack [Cell 2]


Example 3 — Overflowing a full fixed array [Cell 3]

Figure — Stack — LIFO semantics, push - pop - peek, array and linked list implementations

Example 4 — The single-element boundary [Cell 4]


Example 5 — Dynamic growth, no overflow (linked list) [Cell 5]

Figure — Stack — LIFO semantics, push - pop - peek, array and linked list implementations

Example 6 — The order-of-operations bug, side by side [Cell 6]


Example 7 — Real-world word problem: browser Back button [Cell 7]


Example 8 — Exam twist: multi-type bracket matching [Cell 8]

Figure — Stack — LIFO semantics, push - pop - peek, array and linked list implementations

Recall Quick self-test

Pop on an empty stack does what? ::: Raises an error (underflow) — there is no element to return. After push(x) on an array stack, top becomes? ::: old top + 1. Why must pop read before decrementing? ::: After decrement arr[top] points to the element below, returning the wrong value. Why does a counter fail on ([)]? ::: It counts quantity, not bracket type/order; a stack remembers which opener is most recent. A fixed array of capacity n is full when? ::: top == n - 1.

Related: Queue (the FIFO opposite) · DFS uses an explicit/implicit stack.