returning middle element in stack
I have to create a method peek MidElement , so as return the middle element of the stack . So do I have to use an ArrayList, or TORTOISE-HARE algo .
The following is my Class , which has a method named peekMidElement
.
How do I reference Size()
to the ArrayList
.
When I compile the following , I am getting IndexOutOFBoundsExcption at ArrayList.RangeCheck(UnknownSource)
& at ArrayList.get(UnknownSource)
public class SortableStack<E extends Comparable<E>> implements ISortableStack<E> {
private int N;
private Node first;
private ArrayList<E> listOne = new ArrayList<E>();
/* I have to reference the Stack to array list
开发者_高级运维 which I am going use for finding the size of the stack */
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public E peekMidElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size()/2);
}
I cannot see how the code snippet you gave can throw an IndexOutOfBoundsExcption
at the point you have indicated. I conclude that:
the code snippet is not the actual code (e.g. it has been spliced together from a larger class, leaving out some crucial details), or
the exception is not thrown at the place you indicated, or
... this class (which is not thread-safe) is being used in a multi-threaded application without adequate synchronization. The scenario is that some other thread deletes a bunch of elements from
listOne
at exactly the wrong moment. This unlikely, and if it was the cause, the failure would only occur very occasionally.
精彩评论