Mental Model
A stack is a collection where the last item added is the first one to be removed.
Analogy: Think of a stack of plates: you put new plates on top and take plates from the top only.
Top ↑ [ 3 ] [ 2 ] [ 1 ] Bottom
Top ↑ [ 3 ] [ 2 ] [ 1 ] Bottom
Top ↑ [ 1 ] Bottom
Top ↑ [ 2 ] [ 1 ] Bottom
Top ↑ [ 3 ] [ 2 ] [ 1 ] Bottom
Top ↑ [ 2 ] [ 1 ] Bottom
Top ↑ [ 2 ] [ 1 ] Bottom Popped item: 3
import java.util.Stack; public class StackDemo { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); // Push 1 stack.push(1); // add 1 on top // Push 2 stack.push(2); // add 2 on top // Push 3 stack.push(3); // add 3 on top // Pop top item int popped = stack.pop(); // remove top item (3) // Print stack content System.out.println("Stack from top to bottom:"); for (int i = stack.size() - 1; i >= 0; i--) { System.out.println(stack.get(i)); } // Print popped item System.out.println("Popped item: " + popped); } }
stack.push(1); // add 1 on topstack.push(2); // add 2 on topstack.push(3); // add 3 on topint popped = stack.pop(); // remove top item (3)for (int i = stack.size() - 1; i >= 0; i--) {int popped = stack.pop(); // remove top item (3)
stack in Java?push().stack.push(5); correctly uses the stack push method.Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.pop()); System.out.println(stack.pop());
Stack<String> stack = new Stack<>();
stack.push("apple");
stack.push("banana");
String fruit = stack.pop();
System.out.println(stack.peek());
stack.pop();
stack.pop();5 4 3 and leave the stack with elements 1 2 remaining?Pass the test and this pattern moves unknown