Skip to main content

Program in Java to implement stack

 import java.util.Scanner;
class Stack
{
    int top,stk[],max;
    Stack(int cap)
    {
        max=cap;
        top=-1;
        stk = new int[max];
    }
    void push(int data)
    {
        if(top==max-1)
        {
            System.out.println("Stack Overflow");
            return;
        }
        top=top+1;
        stk[top]=data;
    }
    int pop()
    {
        if(top==-1)
        {
            System.out.println("Stack Underflow");
            return -999;
        }
        int data = stk[top];
        top=top-1;
        return data;
    }
    void display()
    {
        if(top==-1)
        {
            System.out.println("Stack Underflow");
            return;
        }
        else
        {
            System.out.println("Elements in the stack are: ");
            for(int i=top;i>=0;i--)
            {
                System.out.println(stk[i]);
            }
        }
    }
    public static void main(String args[])
    {
        Scanner sc =new Scanner(System.in);
        System.out.println("Enter maximum capacity: ");
        int cap = sc.nextInt();
    }
}

Popular posts from this blog