Return the stack element at a given index without modifying the original Stack in Java

眉间皱痕 提交于 2019-12-13 04:47:57

问题


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.

Thanks in advance.


回答1:


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



回答2:


int position =5;

Integer result = stack.get(position);

Java Doc here



来源:https://stackoverflow.com/questions/13507978/return-the-stack-element-at-a-given-index-without-modifying-the-original-stack-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!