0

わかりました、私は最近インタビューでこれを尋ねられました、そして私は興味をそそられました. 基本的に、特定の値のセットを持つスタックがあり、スタック オブジェクトを関数に渡し、特定のインデックスで値を返したいと考えています。ここでの問題は、関数が完了した後、変更されていないスタックが必要だということです。Java はオブジェクトの参照を値で渡すため、注意が必要です。push()、、、およびプリミティブ データ型pop()を使用する純粋な Java の方法があるかどうか、私は興味があり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);

    }

}

クローン作成もコピーであることは理解していますが、それは私が取り除こうとしている基本的な欠陥です。簡略化して、参照の値を渡す代わりに、実際にスタックの値を渡すことができるかどうかを尋ねています。

前もって感謝します。

4

2 に答える 2

6
int position =5;

Integer result = stack.get(position);

Javaドキュメントはこちら

于 2012-11-22T07:51:06.833 に答える
3

別のスタックを使用できない場合は、再帰メソッドを作成することで、同じ目的でコール スタックのローカル変数をごまかして悪用できます。

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);
  }
}
于 2012-11-22T08:29:16.753 に答える