Is this a good way to count items in a stack? im not sure if this is the correct method of implementation
private someList<E> stack;
public int countItems(){
Stack<E> newStack = new Stack<E>();
int count = 0;
while(!stack.isEmpty()){
newStack.push(this.pop());
count++;
}
for(int i = 0; i < count; i++) {
this.push(newStack.pop());
}
return count;
}
public int count() {
return stack.size();
}
Why posting it again? I already answered it in your previous post...
The way you did it is not the way to go because of the O(n) behavior!
With my solution stack.size()
it is in O(1) because the only thing you have to do is ask to the ArrayList
it's size (the ArrayList
explicitly remembers it's size so it can answer your question immediately (without having to count the elements first)).