Saturday, 26 April 2014

Ex 9: Write a program in Java to create a stack class of variable size with push() and pop () methods. Create two objects of stack with 10 data items in both. Compare the top elements of both stack and print the comparison result.

import java.io.*;
class stack
{
int data[]=new int[50];
int sp=0;
int pop()
{
if(sp<=0)
{
System.out.println("Stack is empty");
return(0);
}
else
return(data[sp--]);
}
void push(int a)
{
if(sp>=50)
System.out.println("Stack overflow");
else
data[sp++]=a;
}
}
class s03_03
{
public static void main(String arg[])
{
DataInputStream in=null;
String s;
int d;
stack s1=new stack();
stack s2=new stack();
try
{
in=new DataInputStream(System.in);
for(int i=0;i<10;i++)
{
System.out.println(1+i+") Enter data for the first stack");
s=in.readLine();
d=Integer.parseInt(s);
s1.push(d);
}
for(int i=0;i<10;i++)
{
System.out.println(1+i+") Enter data for the second stack");
s=in.readLine();
d=Integer.parseInt(s);
s2.push(d);
}
if(s1.pop()==s2.pop())
System.out.println("The top of the stacks are same");
else
System.out.println("The top of the stacks are same");
}
catch(Exception e) { System.out.println(e); }
}
}

2 comments: