其他分享
首页 > 其他分享> > 递归逆置栈

递归逆置栈

作者:互联网



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());
        }
    }
}

标签:递归,int,public,Stack,push,test,stack,逆置
来源: https://www.cnblogs.com/chenyi502/p/16408301.html