题目:一个栈一次压入1 2 3 4 5 ,那么从栈顶到栈底分别为 5 4 3 2 1,将这个栈逆序,只能用递归,不能用其他数据结构。
思路:
先设计一个递归函数得到栈底元素
再设计一个递归函数,逆序一个栈
代码实现:
public class Main{
public static void main(String [] args) throws InterruptedException, ParseException {
}
//得到栈底元素
public static int getAndRemoveLastElement(Stack<Integer>stack) {
int result = stack.pop();
if(stack.isEmpty()) {
return result;
}else {
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
//逆序一个栈
public static void reverse(Stack<Integer> stack) {
if(stack.isEmpty()) {
return ;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
}