Saturday, 9 July 2011

Java Collection Stack implementation

Here I am implementing Java collection stack, here I am creating three files
1 is StackADT.java. 2 JCStack.java. 3 JCStack_Test.java

// save it as StackADT
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();


}

// save it as JCStack.java
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=0;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public Object top()
{
return st.peek();
}
public void push(Object element)
{
st.push(element);
top++;
}
public Object pop()
{
try
{
return st.pop();
}
catch (EmptyStackException e )
{
return e.getMessage();
}

}
public void exit()
{
System.exit(0);
}

}

// Save it as JCStack_Test.java
import java.util.Scanner;
class JCStack_Test
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice,el;
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
ST.push(el);
break;
case 2:
System.out.println(ST.isEmpty());
break;
case 3:
System.out.println("top element is ");
System.out.println(ST.top());
break;
case 4:
System.out.println("Poped element is ");
System.out.println(ST.pop());
break;
case 5:
ST.exit();
default:
System.out.println("Plese choose correct choice");


}
}
}
}

No comments:

Post a Comment