Mental Model
A stack adds new items on top, like stacking plates one on another.
Analogy: Imagine a stack of plates: you always put a new plate on the top, never in the middle or bottom.
Top -> null Stack: null
Top -> null Stack: null
Top -> [10] -> null
Top -> [20] -> [10] -> null
Top -> 20 -> 10 -> null
public class Stack { private static class Node { int value; Node next; Node(int value) { this.value = value; this.next = null; } } private Node top; public Stack() { top = null; } public void push(int value) { Node newNode = new Node(value); // create new node with value newNode.next = top; // link new node to current top top = newNode; // update top to new node } public void printStack() { Node current = top; while (current != null) { System.out.print(current.value + " -> "); current = current.next; } System.out.println("null"); } public static void main(String[] args) { Stack stack = new Stack(); stack.push(10); stack.push(20); stack.printStack(); } }
Node newNode = new Node(value); // create new node with valuenewNode.next = top; // link new node to current toptop = newNode; // update top to new nodenewNode.next = top; // link new node to current top
push operation do in a stack?stack in Java?push() to add elements.push() is the correct method to add elements to a stack.Stack<Integer> stack = new Stack<>(); stack.push(5); stack.push(10); stack.push(15); System.out.println(stack);
Stack<String> stack = new Stack<>();
stack.push("Hello");
stack.push(100);Pass the test and this pattern moves unknown