Sunday 16 June 2013

Stack program in java

class StackException extends Exception
{
    private String msg;
    public StackException(String s)
    {
        msg=s;
    }
    public String getErrorMessage()
    {
        return msg;
    }
}
class MyStack
{
    private int stack[];
    public MyStack(int s)
    {
        top=0;
        stack=new int[s];
    }
    void push(int no)
    {
        try
        {
            if(top>2)
                throw new StackException("Stack is full")
                    stack[top]=no;
                    top++;
        }
        catch(StackException e)
        {
            for(int i=top-1;i>=0;i--)
                System.out.println(" "+stack[i);
        }
    }
}
class MyStackDemo
{
    public static void main(String []args)
    {
        MyStack m1=new MyStack(3);
        m1.push(111);
        m1.push(222);
        m1.push(333);
        m1.push(444);
    }
}

No comments: