问题
I am trying to remove a specific element in a stack, but having some trouble. My thought would be to pop the elements on to a temporary stack, pop the index I am looking for and then pop the elements in my temporary stack back onto the main stack. I am having trouble conjuring up how I can get the temp stack back on top. Any help would be greatly appreciated.
public E remove(int index) {
Stack<E> tmpStack = new Stack<E>();
if (size() == 0) {
return null;
} else {
for (int i = 0; i < index; i++) {
tmpStack.push(this.pop());
}
return tmpStack.pop();
}
while (!tmpStack.isEmpty())
this.push(tmpStack.pop());
}
Thoughts? Cheers!
回答1:
The problem is that you have a return before the last revert operation, so method returns with the removed element without calling code after it.
You usually would have an unreachable code error but in your case that's not true since you don't enclose last while inside the else branch so if the stack is empty the while is executed (even on an empty stack) and the java compiler is not able to detect this.
You should do something similar:
if (isEmpty())
return null;
else
{
for (int i = 0; i < index; i++)
tmpStack.push(this.pop());
E removedElement = tmpStack.pop();
while (!tmpStack.isEmpty())
this.push(tmpStack.pop());
return removedElement;
}
回答2:
Accessing elements at a specific index in a stack goes against the point of having a stack.
Other considerations include whether the index refers from the topmost part of your stack.
As mentioned by the others, the problem is that you are returning before you put the elements back into your original stack.
You should also consider the case where the index is greater than the current size of your stack as your current implementation will result in errors. (The Java Stack would throw an EmptyStackException)
来源:https://stackoverflow.com/questions/19647713/removing-a-specific-element-in-a-stack