【问题标题】:Return the stack element at a given index without modifying the original Stack in Java返回给定索引处的堆栈元素,而不修改 Java 中的原始堆栈
【发布时间】:2012-11-10 13:44:56
【问题描述】:

好吧,我最近在一次采访中被问到这个问题,我很感兴趣。基本上我有一个包含一组值的堆栈,我想在函数中传递堆栈对象并返回某个索引处的值。这里的问题是,函数完成后,我需要未修改的堆栈;这很棘手,因为 Java 按值传递对象的引用。我很好奇是否有纯粹的 Java 方法可以使用 push()pop()peek()isempty() 和原始数据类型。我反对将元素复制到数组或字符串中。目前我得到的最干净的是使用克隆,找到下面的代码:

    import java.util.Stack;


public class helloWorld {

public int getStackElement( Stack<Integer> stack, int index ){
    int foundValue=null;//save the value that needs to be returned
    int position=0; //counter to match the index
    Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
    while(position<index)
    {
        System.out.println(altStack.pop());
        position++;
    }
    foundValue=altStack.peek();
    return foundValue;
}

    public static void main(String args[]){
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);
        stack.push(50);
        stack.push(60);
        helloWorld obj= new helloWorld();
            System.out.println("value is-"+obj.getStackElement(stack,4));
        System.out.println("stack is "+stack);

    }

}

我知道克隆也是复制,但这是我要消除的基本缺陷。剥离我是问我是否真的能够传递堆栈的值而不是传递其引用的值。

提前致谢。

【问题讨论】:

  • Java Stack 类扩展了 Vector,所以你可以通过索引获取元素。
  • @nhahtdh:在现实生活中,人们会这样做。不过,我想知道这是否是面试官的目标。
  • @nhahtdh 这是我的第一反应,但正如我所说,或者更确切地说,那个家伙告诉我只使用 push、pop 和 isempty 和原始数据类型。有什么想法吗?
  • @Punkeshwar:只需使用另一个堆栈,然后推送/弹出到下一个堆栈直到到达元素,然后再次推送/弹出以恢复堆栈。
  • @nhahtdh 同意这些是进入某人脑海的最初几个想法。但我认为 THILO 提供的解决方案更接近我想要的。

标签: java reference stack


【解决方案1】:

如果您不能使用另一个堆栈,您可以通过创建递归方法来欺骗和滥用调用堆栈上的局部变量:

public static <T> T getStackElement(Stack<T> stack, int index) {
  if (index == 0) {
    return stack.peek();
  }

  T x = stack.pop();
  try {
    return getStackElement(stack, index - 1);
  } finally {
    stack.push(x);
  }
}

【讨论】:

  • 太棒了,我认为我们可以作弊,因为他将在未来拥有我。我认为这应该可行...谢谢。
【解决方案2】:
int position =5;

Integer result = stack.get(position);

Java 文档here

【讨论】:

  • 我想知道这是否被认为是作弊。通常堆栈没有这个操作(我知道 Java 有)。
  • 另外,我认为您的索引错误。我认为应该是 Vector 的倒数第五个元素(如果 position=1 表示栈顶)。
  • 你说得对,位置 0 表示栈底。 (我只是在我的答案中选择一个随机数)
  • 是的,但是 get(0) 获取堆栈的 bottom 元素(而不是顶部元素)。
  • 类似于nhahtdh提供的,是的,通常Stack没有这个操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2022-11-02
  • 2013-10-13
  • 2021-08-06
  • 1970-01-01
相关资源
最近更新 更多