Friday 6 January 2012

Program to create User defined Stack of type Ineteger


/* Program to create User defined Stack of type Ineteger. */

import java.lang.*;
import java.io.*;
class MyException extends Exception
{
MyException(String str){ super(str); }
}
class MyStack1
{
int size;
int top;
int S[];
MyStack1(int n)
{
size=n;
top=-1;
S=new int[size];
}

void push(int ele)
{
try{
if(top==size-1){throw new MyException("Stack Overflow"); }
S[++top]=ele;
}
catch(Exception e){ System.out.println(e.getMessage()); }
}
int pop()
{
try{
if(top==-1){ throw new MyException("Stack UnderFlow");  }
}
catch(Exception e){ System.out.println(e.getMessage());return S[top]; }
return S[top--];
}
int peek()
{
try{
if(top==-1){ throw new MyException("Stack is Empty");  }
}
catch(Exception e){ System.out.println(e.getMessage());}
return S[top];
}
public static void main(String args[])
{
try
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter Size of the Stack");
String str=dis.readLine();
int val=Integer.parseInt(str);
MyStack1 st=new MyStack1(val);
int ch=0;
System.out.println("\n 1.for PUSH \n 2. for POP \n 3. for PEEK 4 . for EXIT\n Enter Your Choice:");

do
{
str=dis.readLine();
ch=Integer.parseInt(str);
try{
switch(ch)
{
case 1: System.out.print("\n Enter value to push into Stack:");
str=dis.readLine();
st.push(Integer.parseInt(str));
break;
case 2: System.out.println("\n Poped value is:"+st.pop()); break;

case 3:System.out.println("\n Top of the Stack is:"+st.peek()); break;
case 4:System.exit(1);
default:System.out.println("\n Enter Proper Choice"); ch=0;break;
}
}catch(Exception e)
{
System.out.println(e);
}

System.out.println("\n 1.for PUSH \n 2. for POP \n 3. for PEEK 4 . for EXIT\n Enter Your Choice:");
}while(ch<=4);
  }catch(Exception e)
{
System.out.println(e);
}
  

}
}

No comments:

Post a Comment