Monday, February 28, 2011

Stack Using Array Implementation In Java


10:41 AM | , , ,

Stack Using Array Implementation In Java






import java.io.*;
class stk
{
int st[];
int max;
int top;
stk(int n)
{
max=n;
st=new int[n];
top=-1;
}
void push(int a)
{
int b;
b=a;
if(top==max-1)
{
System.out.println("\t\t*****stack is overflow!!!!!******\n");
}
else
{
top=top+1;
st[top]=b;
}
}
void pop()
{
if(top==-1)
{
System.out.println("\t\tstack is underflow!!!!!\n");
}
else
{
int temp;
temp=st[top];
top=top-1;
System.out.println(""+temp+"is deleted\n");
}
}
void display()
{
System.out.println("\n\t\tElements are:");
for(int i=0;i<=top;i++)
{
System.out.println(""+"\t\t"+st[i]);
 
}System.out.println("\n");
}
}
class m
{
static int ch;
 
public static void main(String args[])
{
 
 
stk obj=new stk(5);
 
do
{
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
 
System.out.println("1:push");
 
System.out.println("2:pop");
 
System.out.println("3:display");
System.out.println("4:exit\n");
System.out.println("\t\tenter ur choice\t\t");
ch=Integer.parseInt(b.readLine());
switch(ch)
 
{
case 1:System.out.println("enterthe element to  be inserted=");
 
int c=Integer.parseInt(b.readLine());
obj.push(c);
break;
case 2:
obj.pop();
break;
case 3:
obj.display();
break;
case 4:
System.out.println("exit");
break;
default:
System.out.println("invalid choice\n");
}}
catch(Exception e)
{
System.out.println(e);
}
}
while(ch!=4);
}
}


You Might Also Like :