Java implementation of Stack using Arrays

              Stack is one of the linear data structures which stores data elements. It has following operations.

  • Push() -It is used to insert the data elements to Stack.
  • Pop() – It performs the deletion of element.
  • Peep() – It gives you the top element.
  • isEmpty() -It checks for emptiness
  • isFull() -It checks whether Stack is full or not.

Program:

class StackEg1 {

    private int m_Size;

    private int top;

    private int[] sArray;

    // Here comes the Constructor

    public StackEg1(int size) {

        this.m_Size = size;

        this.sArray = new int[m_Size];

        this.top = -1;

    }

    // insert the element onto the stack(Push)

    public void push(int value) {

        if (isFull()) {

            System.out.println("The Stack is full with elements.Cannot push any element " + value);

            return;

        }

        sArray[++top] = value;

    }

 

    // Delete the element from the stack(pop)

    public int pop() {

        if (isEmpty()) {

            System.out.println("The Stack has no elements. Cannot pop the elements.");

            return -1;

        }

        return sArray[top--];

    }

    // Peek the top element

    public int peek() {

        if (isEmpty()) {

            System.out.println("The Stack is empty. It Cannot peek.");

            return -1;

        }

        return sArray[top];

    }

    // Check for the stack emptiness

    public boolean isEmpty() {

        return (top == -1);

    }

    // Check if the stack is full or not

    public boolean isFull() {

        return (top == m_Size - 1);

    }

    public static void main(String[] args) {

        StackEg1 stack1 = new StackEg1(10);

        stack1.push(11);

        stack1.push(22);

        stack1.push(33);

        stack1.push(44);

        stack1.push(55);

        System.out.println("The top element is: " + stack1.peek());

        System.out.println("The Popped element is: " + stack1.pop());

        System.out.println("The Popped element is: " + stack1.pop());

        System.out.println("The top element is:" + stack1.peek());

        stack1.push(66);

        System.out.println("The top element is after pushing an element:" + stack1.peek());

        if( stack1.isEmpty())

        {

        System.out.println("The stack is empty ");

        }

        else

        {

        System.out.println("The stack is not empty");

        }

    }

}

Output:

C:\raji\blog>javac StackEg1.java

C:\raji\blog>java StackEg1

The top element is: 55

The Popped element is: 55

The Popped element is: 44

The top element is:33

The top element is after pushing an element:66

Thus, the Java Program to implement the Stack using Arrays was done. Keep coding!!!

No comments:

Post a Comment