Think about how functions return in the reverse order of how they were called.
A stack works like a pile of plates: the last plate placed on top is the first one to be taken off. Similarly, the last function called must finish before the previous one continues. This Last In First Out behavior perfectly matches how function calls are managed.
import java.util.Stack; public class StackTest { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.print(stack.pop() + " -> "); System.out.print(stack.peek() + " -> "); System.out.print(stack.pop() + " -> "); System.out.print(stack.pop()); } }
Remember that pop() removes and returns the top element, while peek() only returns the top element without removing it.
The stack after pushes is [10, 20, 30] (30 on top). pop() removes 30, prints it. peek() shows 20. pop() removes 20, prints it. pop() removes 10, prints it.
import java.util.Stack; public class StackError { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("apple"); stack.pop(); stack.pop(); } }
What happens if you try to remove an element from an empty stack?
After the first pop(), the stack is empty. The second pop() tries to remove an element from an empty stack, causing an EmptyStackException.
public boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
return stack.isEmpty();
}Think about how the stack helps track opening parentheses and matches them with closing ones.
The stack stores '(' characters. For each ')', it removes one '(' from the stack. If at the end the stack is empty, all parentheses matched correctly.
Think about which action should be undone first: the last one or the first one?
Undo operations must reverse the last action first, so the Last In First Out order of a stack fits perfectly. A queue would undo actions in the order they were done, which is incorrect for undo.
