递归逆置栈



F函数的作用是把最后一层的删去,并返回,上面的东西盖下来。

public class ReverseStack {

    //目的是把栈中的最底层,删除并返回
    public static int f(Stack<Integer> stack){
        int result = stack.pop();
        if (stack.isEmpty()){
            return result;
        }else {
//            将每次弹出
            int last = f(stack);
            stack.push(result);
            return last;
        }
    }

    public static void reverse(Stack<Integer> stack){
        if (stack.isEmpty()){
            return;
        }
        int i = f(stack);
        reverse(stack);
        stack.push(i);
    }

    public static void main(String[] args) {
        Stack<Integer> test = new Stack<>();
        test.push(1);
        test.push(2);
        test.push(3);
        test.push(4);
        test.push(5);
        reverse(test);
        while (!test.isEmpty()){
            System.out.println(test.pop());
        }
    }
}
posted @ 2022-06-24 11:54  Chenyi_li  阅读(56)  评论(0)    收藏  举报