【发布时间】:2020-08-17 06:19:44
【问题描述】:
public class GetElementWithoutPop {
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);
System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
System.out.println("stack is " + stack);
// Using Java
int position = 3;
Integer result = stack.get(position);
System.out.println(result);
}
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);
}
}
}
直到索引从 3 变为 0 这一切都很好而且很简单,但之后代码返回到 try 块,然后再次返回到 finally 块并且索引开始自行增加,一直返回到3 和stack.push(x) 将堆栈恢复到其原始状态。
这是怎么回事?
对递归相当陌生,我需要了解这一点!
【问题讨论】: