Stack

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.

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.