Stacks

 avatar
unknown
java
a year ago
1.9 kB
2
Indexable
import java.util.*;

public class Stack {
    int a[], size, top;
    Stack(int cap){
        size = cap;
        a = new int[size];
        top = -1;
    }
    void push(int ele) {
        if(top == size-1){
            System.out.println("Stack Overflow");
        }
        else {
            a[++top] = ele;
            System.out.println("Element inserted: "+a[top]);
        }
    }
    void pop() {
        if (top == -1)
            System.out.println("Stack Underflow");
        else {
            System.out.println("Element deleted "+a[top--]);
        }
        display();
    }
    void display() {
        if (top < -1){
            System.out.println("Stack Underflow");
        }
        else {
            System.out.println("Elements are: ");
            for (int i = 0;i <= top;i++){
                System.out.print(a[i] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter capacity: ");
        int capacity = sc.nextInt();
        Stack obj = new Stack(capacity);
        int ch;
        do {
            System.out.println("Enter 1 for Push and 2 for pop, 3 for display and 4 for exit");
            ch = sc.nextInt();
            switch (ch) {
                case 1:
                    System.out.println("Enter the element to enter: ");
                    int ele = sc.nextInt();
                    obj.push(ele);
                    break;
                case 2:
                    obj.pop();
                    break;
                case 3:
                    obj.display();
                    break;
                default:
                    System.out.println("Good Bye!!");
            }
        }while (ch != 4);
    }
}
Editor is loading...
Leave a Comment