Stacks

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that the last element inserted into the stack is the first one to be removed. It can be visualized as a stack of plates, where the last plate placed on top is the first one to be taken out.

Example: Imagine a stack of books. If we want to take a book, we can only remove the topmost book first before accessing the ones below it.

Types of Stacks

There are two primary types of stacks:

  • Static Stack: This type of stack has a fixed size. Once the size is set, it cannot be changed.
  • Dynamic Stack: This stack can grow and shrink in size based on the number of elements it holds, usually implemented using linked lists.

Declaration & Initialization

In Java, a stack can be declared and initialized using the Stack class from the java.util package. Here’s how to declare and initialize a stack:

Basic Operations

Here are the basic operations that can be performed on a stack:

  • Push: Add an element to the top of the stack.
  • Pop: Remove and return the top element from the stack.
  • Peek (Top): View the top element without removing it.
  • isEmpty: Check if the stack is empty.
  • isFull: Check if the stack is full (applicable in fixed-size stacks).

Stack Implementation using Array

Stack Implementation Using Java’s Built-in Stack Class

Advantages & Disadvantages

Advantages Disadvantages
Simple to implement and use. Limited in size (for static stacks).
Helps in undo functionality in applications. Can result in stack overflow if memory is exhausted.
Efficient for recursive function calls. Only the top element can be accessed directly.
Useful in parsing expressions (e.g., parentheses). Not suitable for random access to elements.

Real-world Examples

  • Undo/Redo Functionality: In applications like text editors, a stack is used to store the actions and their reversals, allowing the user to undo or redo actions.
  • Expression Evaluation: Stacks are commonly used in parsing and evaluating mathematical expressions, such as converting infix to postfix or evaluating postfix expressions.
  • Browser History: Stacks are used to store the pages visited in a web browser. When we press the “Back” button, the most recent page is popped from the stack.