Saturday, April 16, 2011

Stack Operations – Push, Pop & Display for Characters


import java.io.IOException;
import java.util.Scanner;
public class Stack_Char
{
    char arr[];
    int top;
   
    Stack_Char()
    {
        arr=new char[30];
        top=-1;
    }

    void Push(char val)
    {
        if(top==30)
            System.out.println("Stack OVerflow");
        else
            arr[++top]=val;
    }
   
    char Pop()
    {
        if(top==-1)
        {
            System.out.println("Stack Underflow");
            return 0;
        }

        else
        {
            return (char)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((char)arr[i] + "-");
        }
        System.out.println(" ");
    }

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

    public static void main(String[] args) throws IOException
    {
        Scanner in = new Scanner(System.in);
        int ch;
        char 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=(char)System.in.read();
                    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");
            }
        }
    }
}