删除堆栈中的特定元素 [英] Removing a specific element in a stack

查看:126
本文介绍了删除堆栈中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除堆栈中的特定元素,但遇到了一些问题.我的想法是将元素弹出到临时堆栈,弹出我正在寻找的索引,然后将临时堆栈中的元素弹出回主堆栈.我无法想象如何让临时堆栈重新回到顶部.任何帮助将不胜感激.

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());
}

想法?干杯!

推荐答案

问题是你在最后一次还原操作之前有一个返回值,所以方法返回了被移除的元素,而没有调用它之后的代码.

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.

您通常会遇到无法访问的代码 错误,但在您的情况并非如此,因为您没有将最后一个 while 包含在 else 分支中,因此如果堆栈为空,则执行 while(即使在一个空堆栈),Java 编译器无法检测到这一点.

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.

你应该做类似的事情:

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

这篇关于删除堆栈中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆