WikiGalaxy

Personalize

Introduction to Stack

What is a Stack?

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Imagine a stack of plates where you can only add or remove the top plate.

Basic Operations

The primary operations of a stack are:

  • Push: Adding an element to the top of the stack.
  • Pop: Removing the top element from the stack.
  • Peek/Top: Viewing the top element without removing it.
  • IsEmpty: Checking if the stack is empty.

      // Diagram Representation of Stack Operations
      // Initial Stack: []
      // Push Operation: [A] -> [B] -> [C]
      // Pop Operation: [A] -> [B]
      // Peek Operation: Top element is B
      // IsEmpty Operation: Returns false
    

      import java.util.Stack;
      
      public class StackExample {
          public static void main(String[] args) {
              Stack stack = new Stack<>();
              
              // Push elements onto the stack
              stack.push("A");
              stack.push("B");
              stack.push("C");
              
              // Display stack
              System.out.println("Stack: " + stack);
              
              // Pop element from the stack
              String poppedElement = stack.pop();
              System.out.println("Popped Element: " + poppedElement);
              
              // Peek at the top element
              String topElement = stack.peek();
              System.out.println("Top Element: " + topElement);
              
              // Check if stack is empty
              boolean isEmpty = stack.isEmpty();
              System.out.println("Is Stack Empty? " + isEmpty);
          }
      }
    

Console Output:

Stack: [A, B, C] Popped Element: C Top Element: B Is Stack Empty? false

Detailed Explanation of Code:

In this example, we demonstrate the basic operations of a stack using Java's built-in Stack class. We start by pushing three elements ("A", "B", "C") onto the stack. The pop operation removes the top element ("C"), and the peek operation retrieves the current top element ("B") without removing it. Finally, the isEmpty operation checks if the stack is empty, returning false since there are still elements in the stack.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025