WikiGalaxy

Personalize

Operations on Stack

Introduction to Stack Operations:

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. The main operations of a stack are Push, Pop, Peek, and isEmpty. These operations allow us to add, remove, and inspect elements in the stack.

Push Operation

Concept:

The push operation adds an element to the top of the stack. If the stack is full, it is said to be in an overflow state.


        // Diagram:
        // Initial Stack: [ ]
        // After push(10): [10]
        // After push(20): [10, 20]

        Stack stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        System.out.println(stack); // Output: [10, 20]
      

Pop Operation

Concept:

The pop operation removes the element at the top of the stack. If the stack is empty, it is said to be in an underflow state.


        // Diagram:
        // Initial Stack: [10, 20]
        // After pop(): [10]
        // Popped Element: 20

        Stack stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        int poppedElement = stack.pop();
        System.out.println(stack); // Output: [10]
        System.out.println("Popped Element: " + poppedElement); // Output: 20
      

Peek Operation

Concept:

The peek operation returns the element at the top of the stack without removing it.


        // Diagram:
        // Stack: [10, 20]
        // Top Element: 20

        Stack stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        int topElement = stack.peek();
        System.out.println("Top Element: " + topElement); // Output: 20
      

isEmpty Operation

Concept:

The isEmpty operation checks whether the stack is empty or not. It returns true if the stack is empty, otherwise false.


        // Diagram:
        // Stack: [10, 20]
        // isEmpty: false

        Stack stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        boolean isEmpty = stack.isEmpty();
        System.out.println("Is Stack Empty? " + isEmpty); // Output: false
      

Search Operation

Concept:

The search operation returns the 1-based position of the element from the top of the stack. If the element is not found, it returns -1.


        // Diagram:
        // Stack: [10, 20, 30]
        // Position of 20: 2

        Stack stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        int position = stack.search(20);
        System.out.println("Position of 20: " + position); // Output: 2
      
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025