Removing a specific element in a stack

10,757

Solution 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;
}

Solution 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)

Share:
10,757
Talaria
Author by

Talaria

Updated on June 14, 2022

Comments

  • Talaria
    Talaria almost 2 years

    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!

  • Talaria
    Talaria over 10 years
    That was exactly it. Thanks for the help!
  • Talaria
    Talaria over 10 years
    Your point is valid and well accepted about a stack not being the best data structure if I want to do something like this. Excellent note on the case if the index is greater than the stack. Thank you!