Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

4.1 Stack Behavior

How it works

A stack pushes and pops at one end, so the most recent item leaves first. That ordering is what makes it match nesting, backtracking, and call stacks.

Reach for a stack whenever the problem involves matching pairs or undoing recent work.

Common error

Treating a stack as a general list and indexing into it, which discards the guarantee that makes it useful.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

Deque<String> stack = new ArrayDeque<String>();
stack.push("A"); stack.push("B");
System.out.println(stack.pop());
System.out.println(stack.peek());

Output

B
A

A stack exposes the most recently added item first. Matching opening and closing delimiters, undo histories, and call-stack models all depend on this last-in-first-out order.

The stack contains A at the bottom and B at the top.
The next pop removes B because the most recent item is on top.

Exercises

4.1.1 · Explain

Starting empty, push 2, push 5, pop, push 7. What values are removed by two more pops?

Show solution

The first pop removes 5. After pushing 7, the next pops remove 7 and then 2.

4.1.2 · Write code

Reverse the values 1, 2, 3 using an ArrayDeque as a stack.

Show solution

Push each value, then pop until empty.

One valid solution

Deque<Integer> s = new ArrayDeque<Integer>();
for (int v : new int[]{1,2,3}) s.push(v);
while (!s.isEmpty()) System.out.print(s.pop() + " ");

Expected output

3 2 1 
Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic