Tuesday, 26 November 2013

STACK program using java

import java.util.Scanner;

class Stack {

    int[] a;
    int top;

    public Stack(int n) {
        a = new int[n];
        top = -1;
    }

    public void push(int val) {
        if (top == a.length - 1) {
            System.out.println("Stack overflow...");
        } else {
            top++;
            a[top] = val;
        }
    }

    public void pop() {
        if (top == -1) {
            System.out.println("Stack underflow...");
        } else {
            System.out.println("Element popped" + a[top]);
            top--;
        }
    }

    public void display() {
        if (top == -1) {
            System.out.println("Stack empty...");
        } else {
            for (int i = top; i >= 0; i--) {
                System.out.println("Stack element: " + a[i]);
            }
        }
    }
}

public class UseStack {

    static public void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Stack s;
        int n;
        System.out.println("Enter the size of the stack: ");
        n = sc.nextInt();
        s = new Stack(n);
        int choice;

        do {
            System.out.println("1.PUSH" + "\n" + "2.POP" + "\n" + "3.DISPLAY" + "\n" + "0.EXIT");
            System.out.println("Enter your choice");
            choice = sc.nextInt();

            switch (choice) {
                case 1:
                    int value;
                    System.out.println("Enter element to push");
                    value = sc.nextInt();
                    s.push(value);
                    break;

                case 2:
                    s.pop();
                    break;

                case 3:
                    s.display();

                case 0:
                    break;

                default:
                    System.out.println("invalid choice...");
            }
        } while (choice != 0);

    }
}