Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Tuesday, 18 March 2014

Java Program for Stack Demonstration

//stack demo
import java.util.*;

class StackDemo
{
    static void StackPush(Stack St,int a)
    {
        St.push(new Integer(a));
        System.out.println("push +a");
        System.out.println("stack:"+St);
    }
    static void Showpop(Stack St)
    {
       
        System.out.println("pop:-");
        Integer a=(Integer)St.pop();
        System.out.println(a);
    }
    public static void main(String args[])
    {
        Stack St=new Stack();
        System.out.println("Stack"+St);
        StackPush(St,42);
        StackPush(St,52);
        StackPush(St,62);
        StackPush(St,72);
        Showpop(St);
        Showpop(St);
        Showpop(St);
        Showpop(St);
   
        try
        {
            Showpop(St);
        }
        catch(EmptyStackException e)
        {
            System.out.println("stack underflow"+e);
        }
    }
}










       

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);
    }
}