Implement Stack Using Array - The Coding Shala

Home >> Data Structures >> Implement Stack Using Array

 In this post, we will learn how to Implement Stack Using Array and will write a Java program for the same.

Implement Stack Using Array

We will implement Stack's operations using an array. If we use an array then it is easy to implement but the size limit is there.

Java Program: 

class MyStack {
    static final int MAX = 1000;
    int top;
    int a[];
 
    boolean isEmpty()
    {
        return (top < 0);
    }
    
    MyStack()
    {
        top = -1;
        a = new int[MAX];
    }
 
    void push(int x)
    {
        if (top >= (MAX - 1)) {
            //stack overflow
            //return false or print error
        }
        else {
            a[++top] = x;
        }
    }
 
    int pop()
    {
        if (top < 0) {
            //stack underflow
            return -1;
        }
        else {
            int x = a[top--];
            return x;
        }
    }
 
    int peek()
    {
        if (top < 0) {
            //stack underflow
            return -1;
        }
        else {
            int x = a[top];
            return x;
        }
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala