Java-Simple Stack Implementation

Simple Stack Implementation

A stack is First in Last Out structure. It has only one point where data enters or leaves. We can’t insert or remove elements into or from the middle of the stack. For now, we’ll just deal with the array representation of the stack.

Program

Program Source

class Stack{
    
    private int stack_array[] = new int[10];
    private int top = -1;
    
    void push(int value)
    {
        top++;
        if(top<10)
        {
            stack_array[top] = value;
        }
        else
        {
            top--;
            System.err.println("Stack Overflow");
        }
    }
    
    int pop()
    {
        if(top == -1)
        {
            System.out.println("Stack Unterflow");
            return 0;
        }
        else
            return stack_array[top--];
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        Stack st = new Stack();
        st.push(10);
        st.push(20);
        st.push(30);
        st.push(40);
        System.out.println(st.pop());
        System.out.println(st.pop());
        System.out.println(st.pop());
        System.out.println(st.pop());
    }
}

Leave a Comment