题目:
一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别位5、4、3、2、1,将这个栈转置后,从栈顶到栈底位1、2、3、4、5,也就是实现找中的元素的逆序,但只能用递归函数来实现,不能用其他数据结构。
思路:
本题考查栈的操作和递归函数的设计,我们需要设计两个递归函数。
递归函数一:将栈stack的栈底元素返回并移除,即每次弹出栈底元素
递归函数二:将栈的元素逆序
package base;import java.util.Stack;public class ReverseStack {public static void main(String[] args) {Stack<Integer> stack = new Stack<Integer>();stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);reverse(stack);System.out.println(stack.toString());}// 弹出栈底元素,非栈底元素弹出后,再压入栈public static Integer popBottomElement(Stack<Integer> stack) {Integer value = stack.pop();if (stack.isEmpty()) {return value;}Integer result = popBottomElement(stack);stack.push(value);return result;}// 逆序public static void reverse(Stack<Integer> stack) {if (stack.isEmpty()) {return;}Integer bottomElement = popBottomElement(stack);reverse(stack);stack.push(bottomElement);}}