仅用递归函数和栈操作逆序一个栈
要求:
- 一个栈依次压入1、2、3、4、5,栈顶到栈底:5、4、3、2、1,转置后,栈顶到栈底:1、2、3、4、5,即实现栈的逆序,但仅仅可用递归实现。
解法
import java.util.Stack;
public class ReverseStackByRecursion {
public static int getAndRemoveLastEle(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveLastEle(stack);
stack.push(result);
return last;
}
}
public static void reserse(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int i = getAndRemoveLastEle(stack);
reserse(stack);
stack.push(i);
}
}