返回给定索引处的堆栈元素而不修改Java中的原始堆栈 [英] Return the stack element at a given index without modifying the original Stack in Java
问题描述
好的,我最近在一次采访中被问到这个问题,我很感兴趣.基本上我有一个带有一组特定值的堆栈,我想在函数中传递堆栈对象并返回特定索引处的值.这里的问题是函数完成后,我需要不修改堆栈;这很棘手,因为 Java 按值传递对象的引用.我很好奇是否有纯粹的 Java 方式来使用 push()
、pop()
、peek()
、isempty()
和原始数据类型.我反对将元素复制到数组或字符串中.目前我得到的最干净的是使用克隆,找到下面的代码:
Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push()
, pop()
, peek()
, isempty()
and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
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);
}
}
我知道克隆也是复制,但这是我要消除的基本缺陷.精简下来,我在问我是否真的能够传递堆栈的值而不是传递其引用的值.
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
提前致谢.
推荐答案
如果你不能使用另一个栈,你可以通过递归方法来欺骗和滥用调用栈上的局部变量:
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
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);
}
}
这篇关于返回给定索引处的堆栈元素而不修改Java中的原始堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!