从栈底取出元素,放入元素到栈底
使用递归算法,不用额外的空间
public static Integer getStackBottom(Stack stack) {
if (stack.empty()) {
return null;
}
//取出栈顶元素
Integer pop = (Integer) stack.pop();
Integer res = getStackBottom(stack);
//判断已到栈底,那么当前的值,就是需要的结果
if (res == null) return pop;
//把已经取出的元素,逐步放回
stack.push(pop);
return res;
}
public static void pushToBottom(Stack stack,Integer value){
if(stack.empty()){
stack.push(value);
return;
}
Integer pop =(Integer) stack.pop();
pushToBottom(stack,value);
stack.push(pop);
}
虽然没有使用额外的存储空间,但是 把变量存储在 方法调用栈里,
一个线程拥有一个方法调用栈,每一个方法都是一个栈帧,