Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack implementation -> Using Arrays

Snippet info

Language

Java

Visibility

public

Author

mataugigen

Created

2025-10-27T03:01:50.446215Z

Updated

2025-10-27T03:01:50.446215Z

class Stack {
    private int[] arr;     // array to store stack elements
    private int top;       // index of the top element
    private int capacity;  // maximum size of the stack

    // Constructor
    public Stack(int size) {
        arr = new int[size];
        capacity = size;
        top = -1; // empty stack
    }

    // Push operation
    public void push(int value) {
        if (isFull()) {
            System.out.println("Stack overflow! Cannot push " + value);
            return;
        }
        arr[++top] = value;
        System.out.println(value + " pushed to stack.");
    }

    // Pop operation
    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack underflow! Nothing to pop.");
            return -1;
        }
        return arr[top--];
    }

    // Peek operation
    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty!");
            return -1;
        }
        return arr[top];
    }

    // Check if stack is empty
    public boolean isEmpty() {
        return top == -1;
    }

    // Check if stack is full
    public boolean isFull() {
        return top == capacity - 1;
    }

    // Display stack elements
    public void display() {
        if (isEmpty()) {
            System.out.println("Stack is empty!");
            return;
        }
        System.out.print("Stack elements: ");
        for (int i = 0; i <= top; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    // Main method for testing
    public static void main(String[] args) {
        Stack stack = new Stack(5);

        stack.push(10);
        stack.push(20);
        stack.push(30);

        stack.display();

        System.out.println("Top element: " + stack.peek());

        stack.pop();
        stack.display();

        stack.pop();
        stack.pop();
        stack.pop();  // underflow example
    }
}
INFO