Stack Implementation using Array in Java

1182
stack implementation in Array using java
Advertisement

In the previous post, we talked about the Stack Data Structure and its implementation in LinkedList. you can read that post here.  And, in this post, we are going to implement the Stack data structure using Array in Java.

Stack Implementation using Array:

Array Implementation of Stack contains 2 classes. Class 1 ie; StackArray.java have the Stack implementation and its method like push(), pop() and display(). Class 2 ie; StackArrayImplementation.java has implemented StackArray.java and provide the implementation for Stack using Array.

StackArray.java

Java
public class StackArray {

    int STACK_SIZE; // Maximum size of the stack
    int[] stack; // Array to store stack elements

    // Constructor: Initializes the stack with the specified size
    public StackArray(int size){
        this.STACK_SIZE = size;
        this.stack = new int[size];
    }

    // Method to push an element onto the stack
    public int push(int top, int ele){
        if(top == STACK_SIZE - 1){
            System.out.println("Stack Overflow.");
        } else {
            top++;
            stack[top] = ele;
        }
        return top;
    }

    // Method to pop an element from the stack
    public int pop(int top){
        if (top == -1){
            System.out.println("Stack Underflow");
        } else {
            System.out.println(String.format("%d removed from the Stack.", stack[top--]));
        }
        return top;
    }

    // Method to display the elements of the stack
    public void display(int top){
        if (top == -1){
            System.out.println("Stack is Empty.");
        } else {
            while(top > 0){
                System.out.print(String.format("%d--->", stack[top]));
                top--;
            }
            System.out.print(String.format("%d--->NULL", stack[top]));
        }
    }

    // Method to get the current size of the stack
    public int stackSize(int top){
        int count = 0;
        int temp = top;
        if (temp == -1){
            return count;
        } else {
            while (temp >= 0){
                ++count;
                temp--;
            }
        }
        return count;
    }
}

This Java class defines a simple stack implementation using an array. Let’s break down the key components and methods:

Explanation:

Constructor (public StackArray(int size))

  • Initializes the stack with the specified size. The size determines the maximum number of elements the stack can hold.

Push Method (public int push(int top, int ele))

  • Pushes an element onto the stack if the stack is not full (top is less than STACK_SIZE - 1).
  • Updates the top index to reflect the new top of the stack.

Pop Method (public int pop(int top))

  • Pops (removes) the top element from the stack if the stack is not empty (top is greater than -1).
  • Displays the removed element and updates the top index.

Display Method (public void display(int top))

  • Displays the elements of the stack from the top to the bottom.

Stack Size Method (public int stackSize(int top))

  • Returns the current size of the stack.

This class provides a basic implementation of a stack using an array with methods for pushing, popping, displaying, and getting the stack size. It’s important to note that this implementation does not handle dynamic resizing of the array if the stack grows beyond its initial size.

StackArrayImplementation:

Java
import java.util.Scanner;

public class StackArrayImplementation {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Get the size of the stack from the user
        System.out.println("Enter the Size of the Stack : ");
        int n = scanner.nextInt();

        System.out.println("=================================");

        // Create an instance of the StackArray class
        StackArray stack = new StackArray(n);

        int top = -1; // Initialize the top of the stack to -1

        // Prompt the user to enter stack elements
        System.out.println("Enter the Stack elements : ");

        // Read 'n' elements from the user and push them onto the stack
        for (int i = 0; i < n; i++) {
            int ele = scanner.nextInt();
            top = stack.push(top, ele);
        }

        System.out.println("=================================");

        // Display the stack after inserting the elements
        System.out.println("Stack after Inserting the elements : ");
        stack.display(top);

        System.out.println();
        System.out.println("=================================");

        // Display the stack size after inserting the elements
        System.out.println("Stack Size after inserting the elements : ");
        System.out.print(stack.stackSize(top));

        System.out.println();

        System.out.println("=================================");

        // Perform pop() operation
        System.out.println("After applying the pop() operation :");
        top = stack.pop(top);

        System.out.println("=================================");

        // Display the stack after the first pop() operation
        System.out.println("Stack after 1st pop() operation performed : ");
        stack.display(top);

        System.out.println();

        System.out.println("=================================");

        // Display the stack size after the first pop() operation
        System.out.println("Stack Size after 1st pop() : ");
        System.out.print(stack.stackSize(top));
        System.out.println();

        System.out.println("=================================");
    }
}

Explanation:

User Input:

  • The program starts by prompting the user to enter the size of the stack (n).

Stack Initialization:

  • An instance of the StackArray class is created, representing a stack with the specified size.

User Input for Stack Elements:

  • The program then prompts the user to enter stack elements. These elements are pushed onto the stack using the push method from the StackArray class.

Display Stack:

  • After inserting elements, the program displays the stack using the display method.

Display Stack Size:

  • It also displays the size of the stack using the stackSize method.

Pop Operation:

  • The program then performs a pop operation using the pop method from the StackArray class.

Display After Pop:

  • After the pop operation, it displays the stack again and its size.

This program essentially demonstrates the basic operations of a stack (push and pop) using an array-based implementation. The user can input the size of the stack and its elements, and the program displays the stack and its size at various points.

Output 1:

Java
Enter the Size of the Stack : 
5
=================================
Enter the Stack elements : 
2
4
5
7
8
=================================
Stack after Inserting the elements : 
8--->7--->5--->4--->2--->NULL
=================================
Stack Size after inserting the elements : 
5
=================================
After applying the pop() operation :
8 removed from the Stack.
=================================
Stack after 1st pop() operation performed : 
7--->5--->4--->2--->NULL
=================================
Stack Size after 1st pop() : 
4
=================================

Output 2:

Java
Enter the Size of the Stack : 
0
=================================
Enter the Stack elements : 
=================================
Stack after Inserting the elements : 
Stack is Empty.

=================================
Stack Size after inserting the elements : 
0
=================================
After applying the pop() operation :
Stack Underflow
=================================
Stack after 1st pop() operation performed : 
Stack is Empty.

=================================
Stack Size after 1st pop() : 
0
=================================

Hope you like this post.

Learn Stack Implementation using LinkedList

You may also learn these to build the Knowledge: