TEN INT JAVA

  Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main method to   illustrate Stack operations

PROGRAM

package jo;

import java.util.*;

 

public class Stack {

    int top; // define top of stack

    int maxsize = 10; // max size of the stack

    int[] stack_arry = new int[maxsize]; // define array that will hold stack elements

 

    Stack() {

        top = -1;

    }

 

    boolean isEmpty() {

        return (top < 0);

    }

 

    boolean push(int val) {

        if (top == maxsize - 1) {

            System.out.println("Stack Overflow !!");

            return false;

        } else {

            top++;

            stack_arry[top] = val;

            return true;

        }

    }

 

    boolean pop() {

        if (top == -1) {

            System.out.println("Stack Underflow !!");

            return false;

        } else {

            System.out.println("Item popped: " + stack_arry[top--]);

            return true;

        }

    }

 

    void display() {

        System.out.println("Printing stack elements..... ");

        for (int i = top; i >= 0; i--) {

            System.out.println(stack_arry[i]);

        }

    }

 

    // ✅ main method

    public static void main(String[] args) {

        Stack stck = new Stack();

        stck.push(10);

        stck.push(20);

        stck.push(30);

        stck.push(40);

 

        System.out.println("\nAfter Push Operation...");

        stck.display();

 

        stck.pop();

        stck.pop();

 

        System.out.println("\nAfter Pop Operation...");

        stck.display();

    }

}

 

}



No comments:

Post a Comment