Mental Model
A stack removes the top item first, like taking the last plate from a stack of plates.
Analogy: Imagine a stack of plates; you always take the top plate off first when you need one.
Top -> [3] -> [2] -> [1] -> null
↑Top -> [3] -> [2] -> [1] -> null
↑Top -> [3] -> [2] -> [1] -> null
Top -> [3] -> [2] -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [2] -> [1] -> null Popped value: 3
class StackNode { int data; StackNode next; StackNode(int data) { this.data = data; this.next = null; } } class Stack { private StackNode top; public Stack() { this.top = null; } public void push(int data) { StackNode newNode = new StackNode(data); newNode.next = top; // link new node to current top top = newNode; // update top to new node } public int pop() { if (top == null) { throw new RuntimeException("Stack is empty"); // handle empty stack } int poppedData = top.data; // save top data top = top.next; // move top to next node return poppedData; // return popped value } public String toString() { StringBuilder sb = new StringBuilder(); StackNode current = top; while (current != null) { sb.append(current.data).append(" -> "); current = current.next; // advance to next node } sb.append("null"); return sb.toString(); } } public class Main { public static void main(String[] args) { Stack stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); System.out.println("Stack before pop: " + stack); int popped = stack.pop(); System.out.println("Popped value: " + popped); System.out.println("Stack after pop: " + stack); } }
if (top == null) { throw new RuntimeException("Stack is empty"); }int poppedData = top.data;top = top.next;return poppedData;current = current.next;if (top == null) { throw new RuntimeException("Stack is empty"); }
top = top.next;
pop() operation do in a stack?pop() removes and returns the top element from the stack.stack in Java?pop() is a method called on the stack object.pop() on the stack instance: stack.pop();Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); int popped = stack.pop(); System.out.println(popped); System.out.println(stack);
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.pop();
stack.pop();
stack.pop();Pass the test and this pattern moves unknown