Saturday, April 16, 2011

Stack Operations – Push, Pop & Display for Numbers


import java.util.Scanner;
public class Stack_Num
{
    double arr[];
    int top;
   
    void Push(double val)
    {
        if(top==9)
            System.out.println("Stack OVerflow");
        else
            arr[++top]=val;
    }
   
    double Pop()
    {
        if(top==-1)
        {
            System.out.println("Stack Underflow");
            return 0;
        }
        else
        {
            return arr[top--];
        }
    }


    void Display()
    {
        if(top==-1)
               System.out.println("Stack is Empty");
        else
        {
            System.out.println("Stack is");
            for(int i=0;i<=top;i++)
                System.out.print(arr[i] + "-");
        }
        System.out.println(" ");
    }

    boolean isEmpty()
    {
        if (top<0)
            return true;
        else
            return false;
    }

    Stack_Num()
    {
        top=-1;
        arr=new double[10];
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int ch,val;
        Stack_Num s=new Stack_Num();
        while(true)
        {
            System.out.println("Choose");
            System.out.println("1 : Push\t2 : Pop\t3 : Display\t4 : Exit");
            ch=in.nextInt();
            switch(ch)
            {
                case 1:
                {
                    System.out.println("Enter Value");
                    val=in.nextInt();
                    s.Push(val);
                    break;
                }
                case 2:
                {
                    System.out.println("Popped Value is " + s.Pop());
                    break;
                }
                case 3:
                {
                    s.Display();
                    break;
                }
                case 4:
                {
                    System.exit(0);
                }
                default:
                    System.out.println("Wrong Choice");
            }
        }
    }
}

No comments:

Post a Comment