Sunday, December 21, 2008

Stack in Java


import java.util.ArrayList;
import java.util.EmptyStackException;

/* Stack class
* A basic stack, you can push items in, last in, is first out.
*
*/
public class Stack {
/// stores my data member in the stack
private ArrayList mItems = new ArrayList();

public Stack()
{
}
/* empty
* -returns true if there are 0 items in the stack
* other wise false
*/
public boolean empty()
{
return mItems.isEmpty();
}
/* size
* -returns the number of items in the stack
*/
public int size()
{
return mItems.size();
}
/*push
* -adds an object to the Top of the stack
*/
public void push(Object obj)
{
mItems.add(obj);
}
/*pop
* -removes the top object from the stack and returns it
* throws EmptyStackException if stack is empty
*/
public Object pop()
{
if (this.empty()) throw new EmptyStackException();

return mItems.remove(mItems.size()-1);

}
/*peek
* -returns the current top object in the stack
* DOES NOT REMOVE IT
*/
public Object peek()
{
if (this.empty()) throw new EmptyStackException();

return mItems.get(mItems.size()-1);
}
}

No comments: