In Java, a Stack is a data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed.
Think of a stack like a stack of plates. You add plates to the top of the stack, and when you want a plate, you take the one from the top. Similarly, in a stack, elements are pushed onto the top, and popped off from the top.
Common Operations
- push(E item): Adds an element to the top of the stack.
- pop(): Removes and returns the element from the top of the stack.
- peek(): Returns the element at the top of the stack without removing it.
- isEmpty(): Checks whether the stack is empty or not.
- size(): Returns the number of elements in the stack.
Example
In Java, you can use the Stack
class from the java.util
package to work with stacks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack<String> stack = new Stack<>(); // Push items onto the stack stack.push("Java"); stack.push("Python"); stack.push("C++"); // Peek at the top item System.out.println("Top element: " + stack.peek()); // Pop the top item System.out.println("Popped item: " + stack.pop()); // Check the size of the stack System.out.println("Size of stack: " + stack.size()); // Check if the stack is empty System.out.println("Is stack empty? " + stack.isEmpty()); } } |
Use Cases
- Undo/Redo Operations: Many applications use stacks to implement undo/redo functionality, where the most recent action is undone first.
- Expression Evaluation: Stacks are useful in parsing and evaluating mathematical expressions, especially in algorithms like converting infix to postfix notation.
- Function Calls (Call Stack): Programming languages use a stack to manage function calls and recursion. Each function call is added to the stack, and when a function finishes, it’s removed from the stack.
- Depth-First Search (DFS): In graph and tree traversal, DFS uses a stack to explore as deeply as possible before backtracking.